package nlib.cmm.fileupload;

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

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

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

/**
 * <pre>
 * @Class Name : DownloadView.java
 * 
 * @Description : 파일 다운로드 VIEW 처리 클래스 
 * 
 * 
 * @프로젝트명: 지방문화원 통합자료관리시스템 구축사업 (2021)
 *
 * </pre>
 *
 * @ ------------    --------    ---------------------------
 * @ 수정일                     수정자             수정내용
 * @ ------------    --------    ---------------------------
 * @ 2021. 8. 3.     KNKIM       최초 생성
 *
 * 
 * @author 이씨플라자 * DIGITALSHIP KNKIM
 * @since 2021. 8. 3.
 * @version 1.0
 *
 */
public class DownloadView extends AbstractView {

	@Override
	protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {

		File file = (File) model.get("downloadFile");

		if(file == null) return;
	
		String fileName = (String) model.get("fname");
		String encfileName = null;
		String userAgent = request.getHeader("User-Agent");

		if (userAgent.indexOf("MSIE") > -1 || userAgent.indexOf("Trident") > -1) {
			encfileName = URLEncoder.encode(fileName, "utf-8").replaceAll("\\+", "%20");
		} else if (userAgent.indexOf("Chrome") > -1) {
			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);
				}
			}
			encfileName = sb.toString();
		} else {
			encfileName = new String(fileName.getBytes("utf-8"));
		}
		
		response.setContentType(getContentType());
		response.setContentLength((int) file.length());
		response.setHeader("Content-Disposition", "attachment; filename=\"" + encfileName + "\";");
		response.setHeader("Content-Transfer-Encoding", "binary");

		try( FileInputStream fis = new FileInputStream(file);
			 OutputStream out = response.getOutputStream())
		{
			FileCopyUtils.copy(fis, out);
			out.flush();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}