package WEB-INF.classes.wenrgise.report.excel;

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.zip.GZIPOutputStream;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import jxl.Workbook;
import jxl.WorkbookSettings;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import wenrgise.report.excel.ExcelReport;
import wenrgise.report.excel.ExcelReportInformation;

public class ExcelReportServlet extends HttpServlet {
  private static final String CONTENT_TYPE_EXCEL = "application/vnd.ms-excel";
  
  private static final String CONTENT_TYPE_ZIP = "application/zip";
  
  public void init(ServletConfig config) throws ServletException {
    super.init(config);
  }
  
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
    processRequest(request, response);
  }
  
  public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
    processRequest(request, response);
  }
  
  private boolean isGzipSupported(HttpServletRequest request) {
    String encodings = request.getHeader("Accept-Encoding");
    return (encodings != null && encodings.indexOf("gzip") != -1);
  }
  
  protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
    response.setContentType("application/zip");
    String reportName = request.getParameter("reportname");
    String inputParam1 = request.getParameter("inputparam1");
    String inputParam2 = request.getParameter("inputparam2");
    ServletOutputStream servletOutputStream = response.getOutputStream();
    GZIPOutputStream gZIPOutputStream = new GZIPOutputStream((OutputStream)servletOutputStream);
    ExcelReport excelReport = new ExcelReport();
    WorkbookSettings ws = excelReport.getWorkBookSetting();
    try {
      WritableWorkbook workbook = Workbook.createWorkbook(gZIPOutputStream, ws);
      WritableSheet s = workbook.createSheet(reportName, 0);
      ExcelReportInformation ex = new ExcelReportInformation(reportName);
      String query = ex.getReportQuery(inputParam1, inputParam2);
      ArrayList aHeader = ex.getReportHeader();
      excelReport.writeDataSheet(s, aHeader, query);
      workbook.write();
      workbook.close();
      gZIPOutputStream.flush();
    } catch (Exception e) {
      e.printStackTrace();
    } 
  }
}
