package wenrgise.hrms.webtier.action;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRRuntimeException;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.util.JRLoader;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import wenrgise.common.exception.EnrgiseApplicationException;
import wenrgise.common.exception.EnrgiseSystemException;
import wenrgise.common.utility.ServiceLocator;
import wenrgise.common.webtier.action.BaseAction;
import wenrgise.hrms.webtier.form.JasperReportForm;

public class ReportViewerAction extends BaseAction {
  private String sDbName = "jdbc/conDS";
  
  public ActionForward executeImpl(ActionMapping mapping, ActionForm form, HttpServletRequest req, HttpServletResponse response) throws EnrgiseApplicationException, EnrgiseSystemException, IllegalAccessException, InvocationTargetException, InstantiationException, ClassNotFoundException, ServletException, IOException {
    JasperReportForm oForm = (JasperReportForm)form;
    req.setAttribute("reportBody", createJasperPrint(req, oForm));
    return mapping.findForward("success");
  }
  
  protected JasperPrint createJasperPrint(HttpServletRequest req, JasperReportForm form) {
    Map reportParams = null;
    if (null != form)
      reportParams = prepareReportInput(req, form); 
    createReportFileName(req, reportParams);
    String repPath = req.getParameter("reportPath");
    System.out.println(String.valueOf("Report Path is ..").concat(String.valueOf(repPath)));
    File reportFile = new File(req.getSession(false).getServletContext().getRealPath(repPath));
    if (!reportFile.exists())
      throw new JRRuntimeException("File WebappReport.jasper not found. The report design must be compiled first."); 
    JasperReport jasperReport = null;
    try {
      jasperReport = (JasperReport)JRLoader.loadObject(reportFile.getPath());
    } catch (JRException e) {
      e.printStackTrace();
      throw new RuntimeException("Exception while loading the report", e);
    } 
    if (null == jasperReport)
      throw new RuntimeException(String.valueOf("Report not found in Path ").concat(String.valueOf(repPath))); 
    if (null == reportParams)
      reportParams = new HashMap(2, 1.0F); 
    reportParams.put("ReportTitle", req.getParameter("title"));
    reportParams.put("BaseDir", reportFile.getParentFile());
    reportParams.put("SUBREPORT_DIR", reportFile.getParentFile().getAbsolutePath());
    Connection conn = null;
    JasperPrint jasperPrint = null;
    try {
      Object dataSourceObj = ServiceLocator.getLocator().getLocalService(this.sDbName);
      DataSource oDataSource = (DataSource)dataSourceObj;
      conn = oDataSource.getConnection();
      jasperPrint = JasperFillManager.fillReport(jasperReport, reportParams, conn);
    } catch (Exception e) {
      e.printStackTrace();
      throw new RuntimeException("Exception while filling the report with data", e);
    } finally {
      if (null != conn)
        try {
          conn.close();
        } catch (SQLException e) {
          throw new RuntimeException("Exception while closing Connection ", e);
        }  
    } 
    return jasperPrint;
  }
  
  private void createReportFileName(HttpServletRequest req, Map reportParams) {
    StringBuffer fileName = new StringBuffer("attachment; filename=\"");
    String repPath = req.getParameter("reportPath");
    String reportName = req.getParameter("reportName");
    if ("C".equalsIgnoreCase(req.getParameter("DOWNLOAD"))) {
      fileName.append(reportName);
      fileName.append(".csv\"");
    } else if ("T".equalsIgnoreCase(req.getParameter("DOWNLOAD"))) {
      fileName.append(reportName);
      fileName.append(".txt\"");
    } else if ("P".equalsIgnoreCase(req.getParameter("DOWNLOAD"))) {
      fileName.append(reportName);
      fileName.append(".pdf\"");
    } else if ("E".equalsIgnoreCase(req.getParameter("DOWNLOAD"))) {
      fileName.append(reportName);
      fileName.append(".xls\"");
    } else {
      fileName.append(reportName);
      fileName.append(".html\"");
    } 
    req.setAttribute("fileName", fileName.toString());
  }
  
  protected Map prepareReportInput(HttpServletRequest req, JasperReportForm form) {
    Map reportInput = (Map)form.getData(req);
    return reportInput;
  }
}
