package com.csc.library.servlet;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.HashMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jxl.Workbook;
import jxl.WorkbookSettings;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;

import com.csc.library.database.StaticProperties;
import com.csc.library.export.JxlExportCsc;
import com.csc.library.service.GenQuqueForExcel;
import com.csc.library.utilities.ThaiUtilities;
import com.csc.library.utilities.UProfile;

public class ExportExcelServlet extends HttpServlet {
	
	HashMap<String,String> paramFilter=new HashMap<String,String>();
	HashMap<String,String> paramOption=new HashMap<String,String>();

	private void setChanel(HttpServletRequest request) {
		Enumeration em = request.getParameterNames();
		String key, value,ind;
        this.paramFilter = new HashMap<String, String>();
        this.paramOption = new HashMap<String, String>();
        ThaiUtilities th = new ThaiUtilities();
		while (em.hasMoreElements()) {
			key = (String) em.nextElement();
			if(key.indexOf("__xlsfilter")>-1){
				ind=key.substring(key.indexOf("__xlsfilter")+1);
				value = th.ASCII2Unicode(request.getParameter(key));
				System.out.println("SET CHANEL Key " + key + " Value " + value);
				this.paramFilter.put(ind, value);
			}else{
				ind=key.substring(key.indexOf("__"));
				value = th.ASCII2Unicode(request.getParameter(key));
				System.out.println("SET CHANEL Key " + key + " Value " + value);
				this.paramOption.put(ind, value);
			}
		}
	}
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
		OutputStream out = null;
		String xlsname=request.getParameter("__xlsname");
		UProfile upro =(UProfile)((UProfile)request.getSession().getAttribute("userprofile")).clone();
		this.setChanel(request);
		WorkbookSettings workbooksetting =null;
		WritableWorkbook copyDocument =null;
		Workbook sourceDocument =null;
		if(upro!=null&&xlsname!=null){
		try {
			GenQuqueForExcel GPO = new GenQuqueForExcel();					
			JxlExportCsc jx = new JxlExportCsc();
			String processID = GPO.createQuquePrintOnline(upro, jx.getEname(),jx.getTname(), "PrintingOnlineExcel", "");			
			try{
				jx.setUProfile(upro);			
				jx.setExcelFile(xlsname);
				jx.setExportFile(processID.concat(".xls"));
				jx.setParamFilter(this.paramFilter);
				jx.setParamOption(this.paramOption);
				jx.export();
				String file_dir="",filename="";
				file_dir=jx.getExportPath();
				filename=jx.getExportFile();
				File file = new File( file_dir, filename );
					// check file
					System.out.println("path=" +file.getCanonicalFile());
					System.out.println("file=" +file.isFile() +", size= "+ file.length() +", exists=" +file.exists() +", canRead=" +file.canRead());
					if ( file.isFile() && file.exists() && file.canRead()) {
						response.reset();
						response.setContentType("application/vnd.ms-excel");
						response.setHeader("Content-Disposition","attachment;filename=\"" + file.getName() + "\"");
						response.setContentLength((int)file.length());
						sourceDocument = Workbook.getWorkbook(file);
						out=response.getOutputStream();
						workbooksetting = new WorkbookSettings();
						workbooksetting.setEncoding("UTF-16");
						copyDocument = Workbook.createWorkbook(response.getOutputStream(), sourceDocument,workbooksetting);	
						copyDocument.write();
						StaticProperties.serverManager.completeProcess(processID, "Process process complete");
					} else{
						System.out.println("File \'" +filename+"\' don't exists or cann't read.");
					}
			}catch(Exception ex){
				StaticProperties.serverManager.incompleteProcess(processID, ex.getMessage());
			}
		} catch (Exception e) {
			throw new ServletException("Exception in Excel Export Servlet", e);
		}finally{
				if(copyDocument!=null){
					try {
						copyDocument.close();
					} catch (WriteException e) {
						e.printStackTrace();
					}
				}
				if(sourceDocument!=null){
					sourceDocument.close();
				}
				   if (out != null)
					    out.close();
			  }
		
		}
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {
		doGet(req, resp);
	}
}