/**
 * @(#)file    FileDownloadServlet.java
 * @(#)author  chj
 * @(#)version 1.0
 * @(#)date    2014-06-24
 * @(#)since   JDK1.6
 *
 * Copyright (c) www.udapsoft.co.kr, Inc.
 */
package kr.co.udapsoft.ebid.buyer.common.file;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

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

import kr.co.hsnc.common.base.WAFLogger;
import kr.co.hsnc.common.config.WAFConfig;
import kr.co.hsnc.common.logger.Logger;
import kr.co.hsnc.common.sql.RowSet;
import kr.co.hsnc.common.util.StringUtil;
import kr.co.hsnc.common.util.Translator;
import kr.co.hsnc.common.util.ValueObject;

import com.oreilly.servlet.MultipartRequest;
import com.udapsoft.waf.common.util.StringUtils;

public class FileDownloadServlet extends HttpServlet {

	public FileDownloadServlet() {

		super();
	}

    public void init(ServletConfig config) throws ServletException {

        super.init(config);
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	WAFLogger.debug("파일 다운 모드:" + request.getParameter("mode"));
    	if(request.getParameter("mode") != null){
    		if(request.getParameter("mode").equals("download")){
    			downloadFile(request, response);
    		}else if(request.getParameter("mode").equals("fpDown")){
    			downloadFileForPath(request, response);
    		}else if(request.getParameter("mode").equals("zipDown")){
    			if("".equals(request.getParameter("zipAutoFile")) || request.getParameter("zipAutoFile") == null){
    				downloadFileZip(request, response);
    			}else if("Y".equals(request.getParameter("zipAutoFile"))){
    				downloadAutoFileZip(request, response);
    			}
    		}
    		else {
    			uploadFile(request, response);
    		}
    	}else{
	        String fileID = request.getParameter("file_id");
	
	        ValueObject fileInfo = FileManager.getFileInfo(fileID);
	
	        String path = StringUtil.replace(WAFConfig.get("waf.repository.path") + fileInfo.get("FILE_PATH"), "/", File.separator);
	        try {
	
	            ServletOutputStream out = response.getOutputStream();
	            File file = new File(path, fileInfo.get("REAL_FILE_NAME"));
	
	            if( file.exists() ) {
	
	                int fileSize = (int)file.length();
	
	                String userAgent = request.getHeader("User-Agent");
	                
	                //System.out.println(fileInfo.get("FILE_NAME"));
	                //System.out.println(Translator.toENG(fileInfo.get("FILE_NAME")));
	                
	                String mimeType = "application/octet-stream";  
	                response.setContentType("application/smnet");
	                //response.setHeader("Content-Disposition", "attachment;filename=" + Translator.translate("UTF-8", "ISO-8859-1", fileInfo.get("FILE_NAME")) + ";");
	                // attachment; 가 붙으면 IE의 경우 무조건 다운로드창이 뜬다. 상황에 따라 써야한다.
	                System.out.println(userAgent.indexOf("MSIE 5.5"));
	                System.out.println(userAgent);
	                if (userAgent != null && userAgent.indexOf("MSIE 7") > -1) { // MS IE 5.5 이하
	                  //response.setHeader("Content-Disposition", "attachment;filename=" + Translator.toENG(fileInfo.get("FILE_NAME")) + ";");
	                	//System.out.println("111111111");
	                  response.setHeader("Content-Disposition", "attachment;filename=" + Translator.toENG(fileInfo.get("FILE_NAME")).replaceAll(",",  "_") + ";");
	                } else if (userAgent != null && userAgent.indexOf("Trident") > -1) { // MS IE (보통은 6.x 이상 가정)
	                	//System.out.println("22222");
	                	response.setHeader("Content-Disposition", "attachment;filename=" + Translator.toENG(fileInfo.get("FILE_NAME")).replaceAll(",",  "_") + ";");
	                } else { // 모질라나 오페라
	                	//System.out.println("333333");
	                	response.setHeader("Content-Disposition", "attachment;filename=" + Translator.translate("UTF-8", "ISO-8859-1", fileInfo.get("FILE_NAME")).replaceAll(",",  "_") + ";");
	                }
	                
	                response.setContentLength(fileSize);
	
	                byte[] buffer = new byte[4096];              
	                BufferedInputStream  bis = new BufferedInputStream(new FileInputStream(file));
	                BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
	
	                int offset = 0;
	                try {             
	
	                    while( (offset = bis.read(buffer)) != -1 ) {
	
	                        bos.write(buffer, 0, offset);
	                    }             
	                    bos.flush();
	                }
	                catch (Exception e) {
	                    Logger.err.printStackTrace(e);
	                }
	                finally {
	
	                    if( bos != null ) try { bos.close(); } catch(Exception e){}
	                    if( bis != null ) try { bis.close(); } catch(Exception e){}
	                }
	            }
	            else {
	
	                out.println("<SCRIPT>");
	                out.println("alert('File not exist.');");
	                out.println("</SCRIPT>");
	                throw new IOException("File Not Found : " + path + File.separator + fileInfo.get("REAL_FILE_NAME"));
	            }
	        }
	        catch(IOException ie) {
	            Logger.err.printStackTrace(ie);
	        }
	        catch(Exception e) {
	            Logger.err.printStackTrace(e);
	        }finally{
	        }
    	}
    }    
    public void downloadFileForPath(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	
		String fileName = request.getParameter("fileName");
		String fileRealName = request.getParameter("fileRealName");
		String filePath = request.getParameter("filePath");
		
		
		String path = StringUtil.replace(WAFConfig.get("waf.repository.path") + filePath, "/", File.separator);
		
		WAFLogger.debug("path====>" + path);
		try {
			
			ServletOutputStream out = response.getOutputStream();
			File file = new File(path, fileRealName);
			
			if( file.exists() ) {
				
				int fileSize = (int)file.length();
				
				String userAgent = request.getHeader("User-Agent");
				
				String mimeType = "application/octet-stream";  
				response.setContentType("application/smnet");
				//response.setHeader("Content-Disposition", "attachment;filename=" + Translator.translate("UTF-8", "ISO-8859-1", fileInfo.get("FILE_NAME")) + ";");
				// attachment; 가 붙으면 IE의 경우 무조건 다운로드창이 뜬다. 상황에 따라 써야한다.
				if (userAgent != null && userAgent.indexOf("MSIE 5.5") > -1) { // MS IE 5.5 이하
					response.setHeader("Content-Disposition", "attachment;filename=" + StringUtils.URLEncode(Translator.translate("8859_1", "UTF-8", fileName)) + ";");
				} else if (userAgent != null && userAgent.indexOf("Trident") > -1) { // MS IE (보통은 6.x 이상 가정)
					response.setHeader("Content-Disposition", "attachment;filename=" + StringUtils.URLEncode(Translator.translate("8859_1", "UTF-8", fileName)) + ";");
				} else { // 모질라나 오페라
					response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ";");
				}
				
				response.setContentLength(fileSize);
				
				byte[] buffer = new byte[4096];              
				BufferedInputStream  bis = new BufferedInputStream(new FileInputStream(file));
				BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
				
				int offset = 0;
				try {             
					
					while( (offset = bis.read(buffer)) != -1 ) {
						
						bos.write(buffer, 0, offset);
					}             
					bos.flush();
				}
				catch (Exception e) {
					Logger.err.printStackTrace(e);
				}
				finally {
					
					if( bos != null ) try { bos.close(); } catch(Exception e){}
					if( bis != null ) try { bis.close(); } catch(Exception e){}
				}
			}
			else {
				
				out.println("<SCRIPT>");
				out.println("alert('File not exist.');");
				out.println("</SCRIPT>");
				throw new IOException("File Not Found : " + path + File.separator + fileRealName);
			}
		}
		catch(IOException ie) {
			Logger.err.printStackTrace(ie);
		}
		catch(Exception e) {
			Logger.err.printStackTrace(e);
		}finally{
		}
    }    
    public void downloadFile(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	String name = request.getParameter("fileName");

    	String fileID = request.getParameter("file_id");

        ValueObject fileInfo = FileManager.getFileInfo(fileID);
        String path = StringUtil.replace(WAFConfig.get("waf.repository.path") + fileInfo.get("FILE_PATH"), "/", File.separator);
        try {

            ServletOutputStream out = response.getOutputStream();
            File file = new File(path, fileInfo.get("REAL_FILE_NAME"));
            if( file.exists() ) {

                int fileSize = (int)file.length();

                String mimeType = "application/unknown";  
                response.setContentType("application/smnet");
                response.setHeader("Content-Disposition", "attachment;filename=" + Translator.toENG(fileInfo.get("REAL_FILE_NAME")) + "\"");
                response.setContentLength(fileSize);
                
                byte[] buffer = new byte[4096];              
                BufferedInputStream  bis = new BufferedInputStream(new FileInputStream(file));
                ServletOutputStream os = response.getOutputStream();
                int r=0;
                byte[] buff=new byte[65536];
                while((r=bis.read(buff))>=0)
                  os.write(buff,0,r);
                
                if( bis != null ) try { bis.close(); } catch(Exception e){}
                if( os != null ) try { os.close(); } catch(Exception e){}
                
            }else {
                throw new IOException("File Not Found : " + path + File.separator + fileInfo.get("REAL_FILE_NAME"));
            }
        }
        catch(IOException ie) {
            Logger.err.printStackTrace(ie);
        }
        catch(Exception e) {
            Logger.err.printStackTrace(e);
        }
    	
    }

    public void downloadFileZip(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	String repoPath = WAFConfig.get("waf.repository.path");
    	String fileName = StringUtil.replace(request.getParameter("fileName"),"/",".") + ".zip";
    	String fileGB = request.getParameter("fileGB");
    	String ID = request.getParameter("ID");
        
        RowSet rowSet = FileManager.getFileList(fileGB, ID);
        try {
        	ServletOutputStream out = response.getOutputStream();
        	if(rowSet.size() > 0){
        		String outDir = repoPath + rowSet.getRow(0).get("FILE_PATH") + "/ZIP";
    			File outDirFile = new File(outDir);
    			if(outDirFile.exists() == false) outDirFile.mkdirs();
    			
        		Map<String, String> fileMap = new HashMap<String, String>();        		
        		for(int i=0; i < rowSet.size(); i++){
        			String filePath = StringUtil.replace(repoPath + rowSet.getRow(i).get("FILE_PATH") + "/" + rowSet.getRow(i).get("REAL_FILE_NAME"), "/", File.separator);
        			File inFile = new File(filePath);
        			if( inFile.exists() ) {        				
        				fileMap.put(filePath, rowSet.getRow(i).get("FILE_NAME"));
        			}
        		}        		
        		
        		String zipPath = StringUtil.replace(outDir + "/" + Translator.translate("8859_1", "UTF-8", fileName) , "/", File.separator);	        	
        		ZipUtil.createZipFile(fileMap, zipPath);
        		
	            File outFile = new File(zipPath);
	
	            if( outFile.exists() ) {
	
	                int fileSize = (int)outFile.length();
	
	                String userAgent = request.getHeader("User-Agent");
	                
	                response.setContentType("application/zip");
					if (userAgent != null && userAgent.indexOf("MSIE 5.5") > -1) { // MS IE 5.5 이하
						response.setHeader("Content-Disposition", "attachment;filename=" + StringUtils.URLEncode(Translator.translate("8859_1", "UTF-8", fileName)) + ";");
					} else if (userAgent != null && userAgent.indexOf("Trident") > -1) { // MS IE (보통은 6.x 이상 가정)
						response.setHeader("Content-Disposition", "attachment;filename=" + StringUtils.URLEncode(Translator.translate("8859_1", "UTF-8", fileName)) + ";");
					} else { // 모질라나 오페라
						response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ";");
					}
	                
	                response.setContentLength(fileSize);
	
	                byte[] buffer = new byte[4096];              
	                BufferedInputStream  bis = new BufferedInputStream(new FileInputStream(outFile));
	                BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
	
	                int offset = 0;
	                try {             
	                    while( (offset = bis.read(buffer)) != -1 ) {	
	                        bos.write(buffer, 0, offset);
	                    }             
	                    bos.flush();
	                }
	                catch (Exception e) {
	                    Logger.err.printStackTrace(e);
	                }
	                finally {	
	                    if( bos != null ) try { bos.close(); } catch(Exception e){}
	                    if( bis != null ) try { bis.close(); } catch(Exception e){}
	                }
	            }
        	}
            else {
                out.println("<SCRIPT>");
                out.println("alert('File not exist.');");
                out.println("</SCRIPT>");
                throw new IOException("File Not Found");
            }
        }
        catch(IOException ie) {
            Logger.err.printStackTrace(ie);
        }
        catch(Exception e) {
            Logger.err.printStackTrace(e);
        }finally{
        }
    }
    
    public void downloadAutoFileZip(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	String repoPath = WAFConfig.get("waf.repository.path");
    	String fileName = StringUtil.replace(request.getParameter("fileName"),"/",".") + ".zip";
    	 
    	RowSet rowSet = null;
    	if(request.getParameter("type").equals("OUT")){
    		String subContModId = request.getParameter("subContModId");
    		rowSet = FileManager.getAutoFileOutList(subContModId);
    	}else{
    		String purContModId = request.getParameter("purContModId");
    		rowSet = FileManager.getAutoFilePurList(purContModId);
    	}
        try {
        	ServletOutputStream out = response.getOutputStream();
        	if(rowSet.size() > 0){
        		String outDir = repoPath + "/cont/"+rowSet.getRow(0).get("FILE_PATH") + "ZIP";
        		System.out.println("outDir : "+outDir);
    			File outDirFile = new File(outDir);
    			if(outDirFile.exists() == false) outDirFile.mkdirs();
        		Map<String, String> fileMap = new HashMap<String, String>();        		
        		for(int i=0; i < rowSet.size(); i++){
        			String filePath = StringUtil.replace(repoPath + "/cont/"+rowSet.getRow(i).get("FILE_PATH") + rowSet.getRow(i).get("UNIQUE_FILE_NAME"), "/", File.separator);
        			System.out.println(i+")filePath : "+filePath);
        			File inFile = new File(filePath);
        			if( inFile.exists() ) {
        				fileMap.put(filePath, rowSet.getRow(i).get("FILE_NAME")+"."+rowSet.getRow(i).get("FILE_EXT"));
        			}
        		}        		
        		String zipPath = StringUtil.replace(outDir + "/" + Translator.translate("8859_1", "UTF-8", fileName) , "/", File.separator);
        		ZipUtil.createZipFile(fileMap, zipPath);
	            File outFile = new File(zipPath);
	
	            if( outFile.exists() ) {
	                int fileSize = (int)outFile.length();
	
	                String userAgent = request.getHeader("User-Agent");
	                response.setContentType("application/zip");
					if (userAgent != null && userAgent.indexOf("MSIE 5.5") > -1) { // MS IE 5.5 이하
						response.setHeader("Content-Disposition", "attachment;filename=" + StringUtils.URLEncode(Translator.translate("8859_1", "UTF-8", fileName)) + ";");
					} else if (userAgent != null && userAgent.indexOf("Trident") > -1) { // MS IE (보통은 6.x 이상 가정)
						response.setHeader("Content-Disposition", "attachment;filename=" + StringUtils.URLEncode(Translator.translate("8859_1", "UTF-8", fileName)) + ";");
					} else { // 모질라나 오페라
						response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ";");
					}
	                response.setContentLength(fileSize);
	
	                byte[] buffer = new byte[4096];     
	                BufferedInputStream  bis = new BufferedInputStream(new FileInputStream(outFile));
	                BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
	
	                int offset = 0;
	                try {             
	                    while( (offset = bis.read(buffer)) != -1 ) {	
	                        bos.write(buffer, 0, offset);
	                    }             
	                    bos.flush();
	                }
	                catch (Exception e) {
	                    Logger.err.printStackTrace(e);
	                }
	                finally {	
	                    if( bos != null ) try { bos.close(); } catch(Exception e){}
	                    if( bis != null ) try { bis.close(); } catch(Exception e){}
	                }
	            }
        	}
            else {
                out.println("<SCRIPT>");
                out.println("alert('File not exist.');");
                out.println("</SCRIPT>");
                throw new IOException("File Not Found");
            }
        }
        catch(IOException ie) {
            Logger.err.printStackTrace(ie);
        }
        catch(Exception e) {
            Logger.err.printStackTrace(e);
        }finally{
        }
    }
    
    public void uploadFile(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	String uppath = request.getParameter("");
    	MultipartRequest multi = new MultipartRequest(request, uppath, 100 * 1024 * 1024, "EUC-KR", new com.oreilly.servlet.multipart.DefaultFileRenamePolicy());
    }
}
