package com.interplug.qcast.util;

import com.fasterxml.jackson.databind.exc.InvalidFormatException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.Map;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.sf.jxls.exception.ParsePropertyException;
import org.jxls.common.Context;
import org.jxls.util.JxlsHelper;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@RequiredArgsConstructor
public class ExcelUtil {

  /**
   * jxls을 이용한 엑셀다운로드
   *
   * @param request HttpServletRequest
   * @param response HttpServletResponse
   * @param map 엑셀 출력데이터
   * @param list 엑셀 출력 목록 데이터
   * @param fileName 다운로드 파일명
   * @param templateFilePath 템플릿 파일경로
   */
  public void download(
      HttpServletRequest request,
      HttpServletResponse response,
      Map<String, Object> map,
      List<Map<String, Object>> list,
      String fileName,
      String templateFilePath)
      throws ParsePropertyException, InvalidFormatException {
    try {
      InputStream is = new BufferedInputStream(new FileInputStream(templateFilePath));

      response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + ".xlsx\"");

      try (OutputStream os = response.getOutputStream()) {
        Context context = new Context();
        context.putVar("data", map);
        context.putVar("list", list);

        JxlsHelper.getInstance().processTemplate(is, os, context);
      }
    } catch (Exception e) {
      log.debug(e.getMessage());
    }
  }
}
