package com.freeman.project.commons;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class FileOper {
	private static final Logger logger = LoggerFactory.getLogger(FileOper.class);
	
	public String createFileName(String fname, int seqno) {
		return fname + "_" + String.valueOf(seqno);
	}

	/** 
	 * @param writer
	 * @throws IOException
	 */
	public void fileMerge(String writeFile,List<String> madefile,HashMap<String, String> commHm) throws IOException {
		logger.debug("begin fileMerge");
		PrintWriter writer = getFileWriter(writeFile);
		String headLine = commHm.get("headLine");
		if(headLine != null && headLine.length() > 0){
			writer.println(headLine);
		}
		for (String fn : madefile) {
			logger.debug("fileMerge,fn=" + fn + "_ic");
			BufferedReader reader = getFileReader(fn + "_ic");
			String line = null;
			while (null != (line = reader.readLine())) {
				logger.debug("3333333line=" + line);
				writer.println(line);
				writer.flush();
			}
			disposeReader(reader);
		}
		deleteTemFile(madefile);
		disposeWriter(writer);
	}

	public void deleteTemFile(List<String> madefile) {
		logger.debug("begin deleteTemFile");
		for (String fn : madefile) {
			File file = new File(fn);
			if (file.isFile()) {
				file.delete();
			}
			File fileic = new File(fn + "_ic");
			if (fileic.isFile()) {
				fileic.delete();
			}
		}

	}

	public BufferedReader getFileReader(String filename) {
		logger.debug("getFileReader exec" + ",filename=" + filename);
		Reader rd = null;
		try {
			rd = new FileReader(new File(filename));
		} catch (FileNotFoundException e) {
			try {
				throw new ICException(e.getMessage());
			} catch (ICException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
		logger.debug("getFileReader end");
		return new BufferedReader(rd);
	}

	public PrintWriter getFileWriter(String filename) {
		logger.debug("getFileWriter exec" + ",filename=" + filename);
		PrintWriter pw = null;
		try {
			pw = new PrintWriter(new File(filename));
		} catch (FileNotFoundException e) {
			try {
				throw new ICException(e.getMessage());
			} catch (ICException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
		logger.debug("getFileWriter end");
		return pw;
	}

	public void disposeReader(Reader fileRead) {
		try {
			if (fileRead != null) {
				fileRead.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void disposeWriter(Writer fileWrite) {
		try {
			if (fileWrite != null) {
				fileWrite.flush();
				fileWrite.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
