package com.siginfo.common;

import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

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

import org.springframework.util.FileCopyUtils;
import org.springframework.web.servlet.view.AbstractView;

public class DownUtil extends AbstractView {
	
	public DownUtil() {
		setContentType("application/octet-stream");
	}
 
    private String check_browser(HttpServletRequest request) {
        String browser = "";
        String header = request.getHeader("User-Agent");
        //신규추가된 indexof : Trident(IE11) 일반 MSIE로는 체크 안됨
        if (header.indexOf("MSIE") > -1 || header.indexOf("Trident") > -1){
            browser = "ie";
        }
        //크롬일 경우
        else if (header.indexOf("Chrome") > -1){
            browser = "chrome";
        }
        //오페라일경우
        else if (header.indexOf("Opera") > -1){
            browser = "opera";
        }
        //사파리일 경우
        else if (header.indexOf("Apple") > -1){
            browser = "sarari";
        } else {
            browser = "firfox";
        }
        return browser;
    }
 
    private String getDisposition(String down_filename, String browser_check) throws UnsupportedEncodingException {
        String prefix = "attachment;filename=";
        String encodedfilename = null;
        
        if (browser_check.equals("ie"))
        {
            encodedfilename = URLEncoder.encode(down_filename, "UTF-8").replaceAll("\\+", "%20");
        }
        else if (browser_check.equals("chrome"))
        {
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < down_filename.length(); i++)
            {
                char c = down_filename.charAt(i);
                if (c > '~')
                {
                    sb.append(URLEncoder.encode("" + c, "UTF-8"));
                } 
                else 
                {
                    sb.append(c);
                }
            }
            encodedfilename = sb.toString();
        }
        else 
        {
            encodedfilename = "\"" + new String(down_filename.getBytes("UTF-8"), "8859_1") + "\"";
        }
        
        return prefix + encodedfilename;
    }

	@Override
	protected void renderMergedOutputModel(Map<String, Object> paramMap,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		// TODO Auto-generated method stub
		
		File file = (File)paramMap.get("downloadExcel");
		
		response.setContentType(getContentType());
		response.setContentLength((int)file.length());
		
		String temp_fileName = file.getName();
		String ori_fileName = getDisposition(temp_fileName, check_browser(request));
		
		response.setHeader("Content-Disposition", ""+ ori_fileName + ";"); // 이부분에 파일이름 파라미터를 넣어주면 된다.
		response.setHeader("Content-Transfer-Encoding", "binary");
		
		OutputStream out = response.getOutputStream();
		FileInputStream fis = null;
		
		try {
			fis = new FileInputStream(file); 
			FileCopyUtils.copy(fis, out);
			//웹서버 파일삭제..
			String filePath = request.getSession().getServletContext().getRealPath("/excelFiles/");
			File xlsFile = new File(filePath,temp_fileName);
			
			if(xlsFile.exists()) xlsFile.delete();
			
		} catch(Exception e) { 
			e.printStackTrace(); 
		} finally { 
			if(fis != null) { 
				try { 
					fis.close(); 
				} catch(Exception e) {} 
			} 
		}
		out.flush(); 
	}
}
