package incheon.res.rdm.com.attachfile.web;

import incheon.res.rdm.com.attachfile.service.RdmComAttachfileService;
import incheon.res.rdm.com.attachfile.vo.RdmComAttachfileVO;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.Map;


@Controller
public class RdmFileDownloadController {

    @Resource
    private RdmComAttachfileService fileService;

    Logger log = Logger.getLogger(this.getClass());
    
    private static String shpFilePath = "e:/shp";

    /**
     * 브라우저 구분 얻기.
     */
    private String getBrowser(HttpServletRequest request) {
        String header = request.getHeader("User-Agent");
        if (header.indexOf("MSIE") > -1) {
            return "MSIE";
        } else if(header.indexOf("Trident") > -1){//ie 11 32bit
        	return "MSIE";
        } else if(header.indexOf("WOW64") > -1){//ie 11 64bit
        	return "MSIE";
        } else if (header.indexOf("Chrome") > -1) {
            return "Chrome";
        } else if (header.indexOf("Opera") > -1) {
            return "Opera";
        }
        return "Firefox";
    }

    /**
     * Disposition 지정하기.
     */
    private void setDisposition(String filename, HttpServletRequest request, HttpServletResponse response) throws Exception {
		String browser = getBrowser(request);

		String dispositionPrefix = "attachment; filename=\"";
		String encodedFilename = null;

		if (browser.equals("MSIE")) {
			encodedFilename = URLEncoder.encode(filename, "UTF-8").replaceAll("\\+", "%20");
		} else if (browser.equals("Firefox")) {
			encodedFilename = "\"" + new String(filename.getBytes("UTF-8"), "8859_1") + "\"";
		} else if (browser.equals("Opera")) {
			encodedFilename = "\"" + new String(filename.getBytes("UTF-8"), "8859_1") + "\"";
		} else if (browser.equals("Chrome")) {
			StringBuffer sb = new StringBuffer();
			for (int i = 0; i < filename.length(); i++) {
				char c = filename.charAt(i);
				if (c > '~') {
					sb.append(URLEncoder.encode("" + c, "UTF-8"));
				} else {
					sb.append(c);
				}
			}
			encodedFilename = sb.toString();
		} else {
			//throw new RuntimeException("Not supported browser");
			throw new IOException("Not supported browser");
		}
		log.error("!!!!"+encodedFilename);
		response.setHeader("Content-Disposition",  dispositionPrefix + encodedFilename+"\";");

		if ("Opera".equals(browser)){
			response.setContentType("application/octet-stream;charset=UTF-8");
		}
    }

    /**
     * 첨부파일로 등록된 파일에 대하여 다운로드를 제공한다.
     */
    @RequestMapping(value = "/rdm/com/attachfile/FileDown.do")
    public void cvplFileDownload(Map<String, Object> commandMap, HttpServletRequest request, HttpServletResponse response) throws Exception {

		 BigDecimal adfIdn = new BigDecimal(request.getParameter("adfIdn"));
    	 //BigDecimal badfIdn = BigDecimal.valueOf(Double.valueOf(adfIdn));
    	 //Boolean isAuthenticated = EgovUserDetailsHelper.isAuthenticated();
    	 Boolean isAuthenticated = true;
		 if (isAuthenticated) {

			RdmComAttachfileVO fileVO = new RdmComAttachfileVO();
		    fileVO.setAdfIdn(adfIdn);
		    RdmComAttachfileVO fvo = fileService.selectFileInf(fileVO);

		    File uFile = new File(fvo.getAdfPth());
		    int fSize = (int)uFile.length();

		    if (fSize > 0) {
		    	log.error("!!!!!!1");
				String mimetype = "application/x-msdownload";

				//response.setBufferSize(fSize);	// OutOfMemeory 발생
				response.setContentType(mimetype);
				//response.setHeader("Content-Disposition", "attachment; filename=\"" + URLEncoder.encode(fvo.getOrignlFileNm(), "utf-8") + "\"");
				setDisposition(fvo.getOrgNam(), request, response);
				response.setContentLength(fSize);

				/*
				 * FileCopyUtils.copy(in, response.getOutputStream());
				 * in.close();
				 * response.getOutputStream().flush();
				 * response.getOutputStream().close();
				 */
				BufferedInputStream in = null;
				BufferedOutputStream out = null;

				try {
				    in = new BufferedInputStream(new FileInputStream(uFile));
				    out = new BufferedOutputStream(response.getOutputStream());
				    FileCopyUtils.copy(in, out);
				    out.flush();
				} catch (IOException ex) {
				    //ex.printStackTrace();
				    // 다음 Exception 무시 처리
				    // Connection reset by peer: socket write error
					log.debug("IGNORED");
				} finally {
				    if (in != null) {
						try {
						    in.close();
						} catch (IOException ignore) {
						    // no-op
							log.debug("IGNORED");
						}
					}

				    if (out != null) {
				    	try {
						    out.close();
						} catch (IOException ignore) {
						    // no-op
							log.debug("IGNORED");
						}
				    }
				}

		    } else {
				/*response.setContentType("application/x-msdownload");

				PrintWriter printwriter = response.getWriter();
				printwriter.println("<html>");
				printwriter.println("<script>alert('bbbbbbbb');</script>");
				printwriter.println("<br><br><br><h2>Could not get file name:<br>" + fvo.getOrgNam() + "</h2>");
				printwriter.println("<br><br><br><center><h3><a href='javascript: history.go(-1)'>Back</a></h3></center>");
				printwriter.println("<br><br><br>&copy; webAccess");
				printwriter.println("</html>");
				printwriter.flush();
				printwriter.close();*/

		    	StringBuffer sb = new StringBuffer();
		    	response.setContentType("text/html;charset=UTF-8");
		    	OutputStream os = response.getOutputStream();

		    	try {
					sb.append("<!DOCTYPE html>");
					sb.append("<html>");
					sb.append("<head>");
					sb.append("<script type=\"text/javascript\">");
					sb.append("alert(\"파일이 없거나 잘못 되었습니다.\");");
					sb.append("window.open('','_self').close();");
					sb.append("</script>");
					sb.append("</head>");
					sb.append("</html>");
					os.write(sb.toString().getBytes("UTF-8"));

		    	} catch(IOException e){
					log.error("I/O error occurred");
		    	} finally {
		    		os.flush();
					os.close();
		    	}
		    }
		}
    }
    
}
