package com.nms.server.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.Ostermiller.util.ExcelCSVParser;
import com.Ostermiller.util.ExcelCSVPrinter;

/**
 *  @date Sep 8, 2011 2:30:14 PM
 *	@author ZhangGang
 *
 */
public class CSVUtils {
	private static Logger logger = Logger.getLogger(CSVUtils.class);
	/**
	 * 获得本机IP
	 * 
	 * @return
	 */
	public static String getLocalIp() {
		String nativeip = "";
		try {
			InetAddress ipv4 = InetAddress.getLocalHost();
			nativeip = ipv4.getHostAddress().toString();

		} catch (Exception e) {
			logger.error(ExceptionPrintUtils.printExceptionStack(e));
		}

		return nativeip;
	}
	
	/**
	 * 写CSV文件，只写入一行
	 *
	 */
	public static boolean csvFilePrinter(File file, String charset, String[] values){
		OutputStreamWriter fos = null;
        try {
        	fos = new OutputStreamWriter(
    				new FileOutputStream(file), charset);
    		
    		
    		ExcelCSVPrinter ecsvp = new ExcelCSVPrinter(fos);
            ecsvp.changeDelimiter(',');
            ecsvp.setAutoFlush(true);
			ecsvp.writeln(values);
			
			fos.flush();
		} catch (IOException e) {
			logger.error(ExceptionPrintUtils.printExceptionStack(e));
			return false;
		}finally {
			if(fos!=null){
				try {
					fos.close();
				} catch (IOException e) {
					logger.error(ExceptionPrintUtils.printExceptionStack(e));
				}
			}
		}
		
		return true;
	}
	
	/**
	 * 写CSV文件，写入多行
	 * 
	 */
	public static byte[] csvBytesPrinter1(List<String[]> values,String charset){
		ExcelCSVPrinter ecsvp = null;
		OutputStreamWriter osw = null;
		ByteArrayOutputStream baos = null;
		byte []  bts = null;
        try {
        	baos = new ByteArrayOutputStream();
			//创建解析信息流
			if(StringUtils.isNotBlank(charset)){
				osw = new OutputStreamWriter(baos, charset);    		
	    		ecsvp = new ExcelCSVPrinter(osw);
			}else{  		
	    		ecsvp = new ExcelCSVPrinter(baos);
			}
			
            ecsvp.changeDelimiter(',');
            ecsvp.setAutoFlush(true);
            if(values!=null && values.size()>0){
            	for(String [] datas : values){
            		ecsvp.writeln(datas);
            	}
            }
			osw.flush();
			bts = baos.toByteArray();
		} catch (IOException e) {
			logger.error(ExceptionPrintUtils.printExceptionStack(e));
			return null;
		}finally {
			try {
				if(ecsvp!=null){ecsvp.close();ecsvp = null;}
				if(baos!=null){baos.close();baos = null;}
				if(osw!=null){osw.close();osw = null;}
			} catch (IOException e) {
				logger.error(ExceptionPrintUtils.printExceptionStack(e));
			}
		}
		return bts;
	}
	
	/**
	 * 写CSV文件，写入多行
	 * 
	 */
	public static byte[] csvFilePrinter(List<List<String>> values,String charset){
		ExcelCSVPrinter ecsvp = null;
		OutputStreamWriter osw = null;
		ByteArrayOutputStream baos = null;
		byte []  bts = null;
        try {
        	baos = new ByteArrayOutputStream();
			//创建解析信息流
			if(StringUtils.isNotBlank(charset)){
				osw = new OutputStreamWriter(baos, charset);    		
	    		ecsvp = new ExcelCSVPrinter(osw);
			}else{  		
	    		ecsvp = new ExcelCSVPrinter(baos);
			}
			
            ecsvp.changeDelimiter(',');
            ecsvp.setAutoFlush(true);
            if(values!=null && values.size()>0){
            	for(List<String> datas : values){
            		ecsvp.writeln((String[])datas.toArray(new String[0]));
            	}
            }
			osw.flush();
			bts = baos.toByteArray();
		} catch (IOException e) {
			logger.error(ExceptionPrintUtils.printExceptionStack(e));
			return null;
		}finally {
			try {
				if(ecsvp!=null){ecsvp.close();ecsvp = null;}
				if(baos!=null){baos.close();baos = null;}
				if(osw!=null){osw.close();osw = null;}
			} catch (IOException e) {
				logger.error(ExceptionPrintUtils.printExceptionStack(e));
			}
		}
		return bts;
	}
	
	public static boolean csvFilePrinter(File file, String charset, List<String[]> values) throws Exception{
		OutputStreamWriter fos = null;
        try {
        	fos = new OutputStreamWriter(
    				new FileOutputStream(file), charset);
    		
    		
    		ExcelCSVPrinter ecsvp = new ExcelCSVPrinter(fos);
            ecsvp.changeDelimiter(',');
            ecsvp.setAutoFlush(true);
            for(String[] val : values){
            	ecsvp.writeln(val);
            }
			
			fos.flush();
		} catch (IOException e) {
			throw e;
		}finally {
			if(fos!=null){
				try {
					fos.close();
				} catch (IOException e) {
				}
			}
		}
		
		return true;
	}
	
	/**
	 * 解析CSV文件缓存 中的指定行
	 * 
	 */
	public static byte[] csvBytesPrinter(List<String> datas,String charset){
		String [] datas0 = new String[0];
		return csvBytesPrinter(datas.toArray(datas0),charset);
	}
	/**
	 * 解析CSV文件缓存 中的指定行
	 * 
	 */
	public static byte[] csvBytesPrinter(String [] datas,String charset){
		ExcelCSVPrinter ecsvp = null;
		OutputStreamWriter osw = null;
		ByteArrayOutputStream baos = null;
		byte []  bts = null;
        try {
        	baos = new ByteArrayOutputStream();
			//创建解析信息流
			if(StringUtils.isNotBlank(charset)){
				osw = new OutputStreamWriter(baos, charset);    		
	    		ecsvp = new ExcelCSVPrinter(osw);
			}else{  		
	    		ecsvp = new ExcelCSVPrinter(baos);
			}
			
            ecsvp.changeDelimiter(',');
            ecsvp.setAutoFlush(true);
			ecsvp.writeln(datas);
			osw.flush();
			bts = baos.toByteArray();
		} catch (IOException e) {
			logger.error(ExceptionPrintUtils.printExceptionStack(e));
			return null;
		}finally {
			try {
				if(ecsvp!=null){ecsvp.close();ecsvp = null;}
				if(baos!=null){baos.close();baos = null;}
				if(osw!=null){osw.close();osw = null;}
			} catch (IOException e) {
				logger.error(ExceptionPrintUtils.printExceptionStack(e));
			}
		}
		return bts;
	}
	/**
	 * 解析CSV文件缓存 中的指定行
	 * 
	 */
	public static String[] csvBytesParser(byte[] fileBts,int rowNum ){
		
		ByteArrayInputStream bais = null;		//字节流对象
		InputStreamReader isr =null;
		ExcelCSVParser csvParser = null;		//CSV解析对象
		String[] currLine = null;
		
        try {
        	
        		 bais = new ByteArrayInputStream(fileBts);
        		 UnicodeReader unicodeReader = new UnicodeReader(bais,Charset.defaultCharset().name());
        		 csvParser = new ExcelCSVParser(unicodeReader);
        	
            while(true){
            	currLine = csvParser.getLine();
            	if(currLine == null){
            		break;
            	}
            	if(rowNum == csvParser.getLastLineNumber()){
            		break;
            	}else{
            		currLine = null;
            	}
            }
		} catch (IOException e) {
			logger.error(ExceptionPrintUtils.printExceptionStack(e));
			return null;
		}finally {
			try {
				if(csvParser!=null){csvParser.close();csvParser = null;}
				if(isr!=null){isr.close();isr = null;}
				if(bais!=null){bais.close();bais = null;}
			} catch (IOException e) {
				logger.error(ExceptionPrintUtils.printExceptionStack(e));
			}
		}
		
		return currLine;
	}
	/**
	 * 解析CSV文件缓存 中的指定行
	 * 
	 */
	public static String[] csvBytesParser(byte[] bts, String charset,int rowNum ){
		
		ByteArrayInputStream bais = null;		//字节流对象
		InputStreamReader isr =null;
		ExcelCSVParser csvParser = null;		//CSV解析对象
		String[] currLine = null;
		
        try {
        	
        	 //创建解析信息流
        	 if(StringUtils.isNotBlank(charset)){
        		 bais = new ByteArrayInputStream(bts);
        		 String encode = new UnicodeReader(bais,charset).getEncoding();
        		 charset = StringUtils.isBlank(encode)?charset:encode;
        		 isr = new InputStreamReader(bais,charset);
        		 csvParser = new ExcelCSVParser(isr);
        	 }else{
        		 bais = new ByteArrayInputStream(bts);
        		 csvParser = new ExcelCSVParser(bais);
        	 }
            
            while(true){
            	currLine = csvParser.getLine();
            	if(currLine == null){
            		break;
            	}
            	if(rowNum == csvParser.getLastLineNumber()){
            		break;
            	}else{
            		currLine = null;
            	}
            }
		} catch (IOException e) {
			logger.error(ExceptionPrintUtils.printExceptionStack(e));
			return null;
		}finally {
			try {
				if(csvParser!=null){csvParser.close();csvParser = null;}
				if(isr!=null){isr.close();isr = null;}
				if(bais!=null){bais.close();bais = null;}
			} catch (IOException e) {
				logger.error(ExceptionPrintUtils.printExceptionStack(e));
			}
		}
		
		return currLine;
	}
	/**
	 * 解析CSV文件缓存 中的所有行
	 * 
	 */
	public static List<String[]> csvBytesParser(byte[] bts, String charset ){
		
		ByteArrayInputStream bais = null;		//字节流对象
		InputStreamReader isr =null;
		ExcelCSVParser csvParser = null;		//CSV解析对象
		List<String[]> allLine = new ArrayList<String[]>();
		String[] currLine = null;
		
		try {
			
			//创建解析信息流
			if(StringUtils.isNotBlank(charset)){
				bais = new ByteArrayInputStream(bts);
				String encode = new UnicodeReader(bais,charset).getEncoding();
				charset = StringUtils.isBlank(encode)?charset:encode;
				isr = new InputStreamReader(bais,charset);
				csvParser = new ExcelCSVParser(isr);
			}else{
				bais = new ByteArrayInputStream(bts);
				csvParser = new ExcelCSVParser(bais);
			}
			
			while(true){
				currLine = csvParser.getLine();
				if(currLine == null){
					break;
				}else {
					allLine.add(currLine);
				}				
			}
		} catch (IOException e) {
			logger.error(ExceptionPrintUtils.printExceptionStack(e));
			return null;
		}finally {
			try {
				if(csvParser!=null){csvParser.close();csvParser = null;}
				if(isr!=null){isr.close();isr = null;}
				if(bais!=null){bais.close();bais = null;}
			} catch (IOException e) {
				logger.error(ExceptionPrintUtils.printExceptionStack(e));
			}
		}
		
		return allLine;
	}
	
	/**
	 * 解析CSV文件中的指定行
	 * 
	 */
	public static String[] csvFileParser(File file, String charset, int rowNum){
		//InputStream in = null;
		InputStreamReader inputStreamReader = null;		//字节流对象
		ExcelCSVParser csvParser = null;		//CSV解析对象
		String[] currLine = null;
        try {
        	 //创建解析信息流
            inputStreamReader = new InputStreamReader(new FileInputStream(file),charset);
            csvParser = new ExcelCSVParser(inputStreamReader);
            while(true){
            	currLine = csvParser.getLine();
            	if(currLine == null){
            		break;
            	}
            	if(rowNum == csvParser.getLastLineNumber()){
            		break;
            	}else{
            		currLine = null;
            	}
            }
		} catch (IOException e) {
			logger.error(ExceptionPrintUtils.printExceptionStack(e));
			return null;
		}finally {
			try {
				if(csvParser!=null){csvParser.close();csvParser = null;}
				if(inputStreamReader!=null){inputStreamReader.close();inputStreamReader = null;}
			} catch (IOException e) {
				logger.error(ExceptionPrintUtils.printExceptionStack(e));
			}
		}
		
		return currLine;
	}
	
	/**
	 * 解析CSV文件的所有行
	 * 
	 */
	public static List<String[]> csvFileParser(File file, String charset){
		//InputStream in = null;
		InputStreamReader inputStreamReader = null;		//字节流对象
		ExcelCSVParser csvParser = null;		//CSV解析对象
		List<String[]> allLineList = null;
        try {
        	 //创建解析信息流
            inputStreamReader = new InputStreamReader(new FileInputStream(file),charset);
            csvParser = new ExcelCSVParser(inputStreamReader);
        	String[] currLine = null;
        	while((currLine=csvParser.getLine())!=null){
        		allLineList.add(currLine);
        	}
		} catch (IOException e) {
			logger.error(ExceptionPrintUtils.printExceptionStack(e));
			return null;
		}finally {
			try {
				if(csvParser!=null){csvParser.close();csvParser = null;}
				if(inputStreamReader!=null){inputStreamReader.close();inputStreamReader = null;}
			} catch (IOException e) {
				logger.error(ExceptionPrintUtils.printExceptionStack(e));
			}
		}
		return allLineList;
	}

}
