package com.madeu.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.DecimalFormat;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.FileCopyUtils;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

public class FileDownloadUtil {
	
	static Logger logger = LoggerFactory.getLogger(FileDownloadUtil.class);
	
	public static void fileDownload(HttpServletRequest request, HttpServletResponse response, String filePath, String oFileName, String cFileName) 
	throws IOException{
		//filePath = filePath.replace(cFileName, "");
	
		File file = new File(filePath + "\\" + cFileName);
		
		logger.debug("root     : " + filePath);
		
		
		if(file.exists() && file.isFile()) {
			logger.debug("file exists ");
			
			response.setContentType("application/octet-stream; charset=utf-8");
			response.setContentLength((int)file.length());
			
			String browser = getBrowser(request);
			String disposition = getDisposition(oFileName, browser);
			
			response.setHeader("Content-Disposition", disposition);
			response.setHeader("Content-Transfer-Encoding", "binary");
			
			OutputStream out = response.getOutputStream();
			
			FileInputStream fis = null;
			
			fis = new FileInputStream(file);
			FileCopyUtils.copy(fis, out);
			
			if(fis != null) {
				fis.close();
			}
			
			out.flush();
			out.close();
		}else {
			logger.debug("file exists not");
		}
	}
	
	
	public static void fileDownload(HttpServletRequest request, HttpServletResponse response, String filePath, String oFileName) 
			throws IOException{
		//filePath = filePath.replace(cFileName, "");
		
		File file = new File(filePath);
		
		logger.debug("root     : " + filePath);
		
		
		if(file.exists() && file.isFile()) {
			logger.debug("file exists ");
			
			response.setContentType("application/octet-stream; charset=utf-8");
			response.setContentLength((int)file.length());
			
			String browser = getBrowser(request);
			String disposition = getDisposition(oFileName, browser);
			
			response.setHeader("Content-Disposition", disposition);
			response.setHeader("Content-Transfer-Encoding", "binary");
			
			OutputStream out = response.getOutputStream();
			
			FileInputStream fis = null;
			fis = new FileInputStream(file);
			FileCopyUtils.copy(fis, out);
			
			if(fis != null) {
				fis.close();
			}
			
			out.flush();
			out.close();
		}else {
			logger.debug("file exists not");
		}
	}
	
	
	private static String getBrowser(HttpServletRequest request) {
		String header = request.getHeader("User-Agent");
		if (header.indexOf("MSIE") > -1 || header.indexOf("Trident") > -1)
			return "MSIE";
		else if (header.indexOf("Chrome") > -1)
			return "Chrome";
		else if (header.indexOf("Opera") > -1)
			return "Opera";
		return "Firefox";
	}

	private static String getDisposition(String filename, String browser) throws UnsupportedEncodingException {
		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")) {
			encodedFilename = "\"" + new String(filename.getBytes("UTF-8"), "8859_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);
				}
			}
			encodedFilename = sb.toString();
			*/
		}
		return dispositionPrefix + encodedFilename;
	}
	
	public static String byteCalculate(String bytes) {
		String retFormat = "0";
		Double size = Double.parseDouble(bytes);
		
		String[] s = { "bytes", "KB", "MB", "GB", "TB", "PB" };
		
		if (bytes != "0") {
			int idx = (int) Math.floor(Math.log(size) / Math.log(1024));
			DecimalFormat df = new DecimalFormat("#,###.##");
			double ret = ((size / Math.pow(1024, Math.floor(idx))));
			retFormat = df.format(ret) + " " + s[idx];
		} else {
			retFormat += " " + s[0];
		}
		
		return retFormat;
	}
}
