package com.dbnt.faisp.util;

import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFDataFormat;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import org.springframework.ui.Model;
import org.springframework.util.FileCopyUtils;



import com.dbnt.faisp.util.ParamMap;

public class Utils {
	

	public static boolean isEmpty(final Object obj) {
    	return !isNotEmpty(obj);
    }

	public static boolean isNotEmpty(final Object obj) {
		if(null == obj) return false;
		else {
			if(obj instanceof String) return "".equals(obj) ? false : true;
			else if(obj instanceof List) return !((List<?>)obj).isEmpty();
			else if(obj instanceof Map) return !((Map<?,?>)obj).isEmpty();
//			else if(obj instanceof Object[]) return 0 == Array.getLength(obj) ? false : true;
			else if(obj instanceof Integer) return !(null == obj);
			else if(obj instanceof Long) return !(null == obj);
			else return false;
		}
	}

	public static String getTimeStampString(final String format) {
    	return getTimeStampString(new Date(), format);
    }
	
	public static String getTimeStampString(final Date date) {
		return getTimeStampString(date, "yyyyMMddHHmmss");
	}
    
    public static String getTimeStampString(final Date date, final String format){
    	java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat (format, java.util.Locale.KOREA);
    	return formatter.format(date);
    }
    
    public static String getTimeStampString(String date, final String format) {
    	try {
    	    if(null == date || "".equals(date)) return "";
    	    
    	    Date	d	= null;
    	    		date= date.replaceAll("-", "");
    	    
    	    switch(date.length()) {
    	    	case 14: break;
    	    	case 12: date += "00";			break;
    	    	case 10: date += "0000";		break;
    	    	case 8:	 date += "000000";		break;
    	    	case 6:	 date += "01000000";	break;
    	    	case 4:	 date += "0101000000";	break;
    	    	default: return "";
    	    }
    	    
    		java.text.SimpleDateFormat tmpFormat = new java.text.SimpleDateFormat("yyyyMMddHHmmss", java.util.Locale.KOREA);

	    	if("".equals(date)) d = new Date();
	    	else {
	    	    tmpFormat.setLenient(true);
	    		d = tmpFormat.parse(date);
	    	}
	    	
	    	return getTimeStampString(d, format);
    	} catch(Exception e) {
    		e.printStackTrace();
    		return "";
    	}
    }
	
	public static void listToExcel(List<ParamMap> list, HttpServletResponse response, String[] headers, String[] headerNames, String[] columnType, String sheetName, String excelFileName) throws IOException {
		if(Utils.isNotEmpty(list)) {
			// 메모리에 100개의 행을 유지합니다. 행의 수가 넘으면 디스크에 적습니다. 
			XSSFWorkbook wb = new XSSFWorkbook(); 
			Sheet sheet = wb.createSheet(sheetName);
			Row headerRow = sheet.createRow(0);
			CellStyle cellStyle1 = wb.createCellStyle();		//쉼표들어간 숫자 양식
			CellStyle cellStyle2 = wb.createCellStyle();		//숫자양식
			CellStyle headerStyle = wb.createCellStyle();		//숫자양식
			
			XSSFDataFormat format = wb.createDataFormat();
			cellStyle1.setDataFormat(format.getFormat("#,##0"));			
			cellStyle2.setDataFormat(format.getFormat("#"));
			headerStyle.setAlignment(HorizontalAlignment.CENTER);
			headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
			headerStyle.setFillForegroundColor((short)3);
			headerStyle.setFillForegroundColor(IndexedColors.LIME.getIndex());
			
			for(int i=0; i<list.size(); i++) {
				ParamMap rowData = list.get(i);
				Row row = sheet.createRow(i+1);
				
				for(int j=0; j<headers.length; j++) {
					Cell cell = row.createCell(j);
					
					if(columnType[j].equalsIgnoreCase("Money")) {
						cell.setCellValue(rowData.getInt(headers[j]));
						cell.setCellStyle(cellStyle1);
					} else if(columnType[j].equalsIgnoreCase("Int")) {
						cell.setCellValue(rowData.getInt(headers[j]));
						cell.setCellStyle(cellStyle2);
					} else if(columnType[j].equalsIgnoreCase("String")) {
						cell.setCellValue(rowData.getString(headers[j]));
					} else {
						cell.setCellValue(rowData.getString(headers[j]));
					}
				}
			}
			
			for(int j=0; j<headerNames.length; j++) {
				Cell cell = headerRow.createCell(j);
				cell.setCellValue(headerNames[j]);
				cell.setCellStyle(headerStyle);
				sheet.autoSizeColumn(j);
				sheet.setColumnWidth(j, (sheet.getColumnWidth(j)) + 1000);
			}
			//엑셀이름 한글깨짐방지
			 String outputFileName = new String(excelFileName.getBytes("KSC5601"), "8859_1");
			 
			response.setHeader("Set-Cookie", "fileDownload=true; path=/"); 
			response.setHeader("Content-Disposition", String.format("attachment; filename=\""+outputFileName+"_"+Utils.getTimeStampString("yyyyMMdd_HHmm")+".xlsx\""));

			wb.write(response.getOutputStream());
			wb.close();
		} else {
			response.setHeader("Content-Type", "text/html; charset=UTF-8");
			PrintWriter		out	= response.getWriter();
			
			out.write("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">");
			out.write("<html lang=\"ko\">");
			out.write("<head>");
			out.write("<script type=\"text/javascript\">");
			out.write("alert('데이터가 없습니다.');");
			out.write("history.back(-1);");
			out.write("</script>");
			out.write("</head>");
			out.write("</html>");
			
			out.flush();
			out.close();
		}

	}
	
	
		

}
