package egovframework.util.excel;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;

public class OutputExcelFile {

	public void serveFile(HttpServletRequest request, HttpServletResponse response, Path filePath) throws IOException {

		String fileName = filePath.getFileName().toString();
		try {
			String browser = request.getHeader("User-Agent");
			String encodedFileName;
			if (browser.contains("MSIE") || browser.contains("Trident")) {
				// IE 브라우저 대응
				encodedFileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
			} else {
				// IE 외 브라우저 대응 (크롬, 파이어폭스 등)
				encodedFileName = new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
			}
			// Content-Disposition 설정
			response.setHeader("Content-Disposition", "attachment; filename=\"" + encodedFileName + "\"");
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e.getMessage());
		}

		try (InputStream is = Files.newInputStream(filePath);
			 OutputStream os = response.getOutputStream()) {
			byte[] buffer = new byte[1024];
			int bytesRead;
			while ((bytesRead = is.read(buffer)) != -1) {
				os.write(buffer, 0, bytesRead);
			}
			os.flush();
		}
	}

	public void generateExcelFile(ExcelSheetData data, Path filePath) throws IOException {
		try (OutputStream os = Files.newOutputStream(filePath)) {
			new SxssfExcelFile(data, os, null); // 엑셀 파일 생성 및 저장
		}
	}

}
