/* 
 * $Id: GenericJasperReportsViewHandler.java,v 1.5 2009-09-22 15:00:54 soledad Exp $
 * 
 * Copyright (c) 2006 Neogia - www.neogia.org
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 */
package org.ofbiz.webapp.view;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.jasperreports.engine.JRAbstractExporter;
import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JREmptyDataSource;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.data.JRMapCollectionDataSource;
import net.sf.jasperreports.engine.export.JRCsvExporter;
import net.sf.jasperreports.engine.export.JRHtmlExporter;
import net.sf.jasperreports.engine.export.JRPdfExporter;
import net.sf.jasperreports.engine.export.JRRtfExporter;
import net.sf.jasperreports.engine.export.JRXlsExporter;

import org.ofbiz.base.location.FlexibleLocation;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.UtilHttp;
import org.ofbiz.base.util.UtilProperties;
import org.ofbiz.base.util.cache.UtilCache;
import org.ofbiz.webapp.control.ContextFilter;
import org.ofbiz.entity.GenericDelegator;
import org.ofbiz.entity.jdbc.ConnectionFactory;

/**
 * Handles JasperReports PDF view rendering
 *
 * @author     <a href="mailto:jonesde@ofbiz.org">David E. Jones</a>
 * @version    $Rev: 5966 $
 * @since      2.0
 */
public class GenericJasperReportsViewHandler extends AbstractViewHandler {
    
    public static final String module = GenericJasperReportsViewHandler.class.getName();

    protected ServletContext context;
    public static UtilCache jasperReportsCompiledCache = UtilCache.createUtilCache("webapp.JasperReportsCompiled");

    public void init(ServletContext context) throws ViewHandlerException {
        this.context = context;
    }

    public void render(String name, String page, String info, String contentType, String encoding, HttpServletRequest request, HttpServletResponse response) throws ViewHandlerException {
        // some containers call filters on EVERY request, even forwarded ones,
        // so let it know that it came from the control servlet

        if (request == null) {
            throw new ViewHandlerException("The HttpServletRequest object was null, how did that happen?");
        }
        if (page == null || page.length() == 0) {
            throw new ViewHandlerException("View page was null or empty, but must be specified");
        }
        if (info == null || info.length() == 0) {
            Debug.logInfo("View info string was null or empty, (optionally used to specify an Entity that is mapped to the Entity Engine datasource that the report will use).", module);
        }

        // tell the ContextFilter we are forwarding
        request.setAttribute(ContextFilter.FORWARDED_FROM_SERVLET, new Boolean(true));
        GenericDelegator delegator = (GenericDelegator) request.getAttribute("delegator");
        if (delegator == null) {
            throw new ViewHandlerException("The delegator object was null, how did that happen?");
        }
        
        URL reportFileUrl = null;
        try {
            reportFileUrl = FlexibleLocation.resolveLocation(page);
        } catch (MalformedURLException e1) {
            Debug.logError("Could not find Entity Data document in resource: " + page + "; error was: " + e1.toString(), module);
        }
        
        try {           
            JasperReport report = (JasperReport) jasperReportsCompiledCache.get(page);
            if (report == null) {
                synchronized (this) {
                    report = (JasperReport) jasperReportsCompiledCache.get(page);
                    if (report == null) {
                        report = JasperCompileManager.compileReport(reportFileUrl.openStream());
                        jasperReportsCompiledCache.put(page, report);
                    }
                }
            }
            
            Map parameters = (Map) request.getAttribute("jrParameters");
            if (parameters == null) {
                parameters = UtilHttp.getParameterMap(request);
            }
            //if local is not defined, define it
            Locale locale = UtilHttp.getLocale(request);
            if (!parameters.containsKey("REPORT_LOCALE")){
                parameters.put("REPORT_LOCALE", locale);
            }
            parameters.putAll(UtilProperties.getProperties("CommonUiLabels", locale));
            
            JRDataSource jrDataSource = null;
            if (request.getAttribute("records") != null ){
                Object records = request.getAttribute("records");
                if (request.getAttribute("records") instanceof JRDataSource) {
                    jrDataSource = (JRDataSource) records;
                }
                else {
                    jrDataSource = new JRMapCollectionDataSource((List)records);
                }
            }
            else {
                jrDataSource = (JRDataSource) request.getAttribute("jrDataSource");
            }

            JasperPrint jp = null;
            if (jrDataSource == null) {
                String datasourceName = delegator.getEntityHelperName(info);
                if (datasourceName != null && datasourceName.length() > 0) {
                    Debug.logInfo("Filling report with connection from datasource: " + datasourceName, module);
                    jp = JasperFillManager.fillReport(report, parameters, ConnectionFactory.getConnection(datasourceName));
                } else {
                    Debug.logInfo("Filling report with an empty JR datasource", module);
                    jp = JasperFillManager.fillReport(report, parameters, new JREmptyDataSource());
                }
            } else {
                Debug.logInfo("Filling report with a passed in jrDataSource", module);
                jp = JasperFillManager.fillReport(report, parameters, jrDataSource);
            }

            if (jp.getPages().size() < 1) {
                throw new ViewHandlerException("Report is Empty (no results?)");
            } else {
                Debug.logInfo("Got report, there are " + jp.getPages().size() + " pages.", module);
            }

            String reportContentType = request.getParameter("reportContentType");
            Debug.logInfo("Report contentType=" + reportContentType, module);
            if (reportContentType != null && reportContentType.length() > 0) {
                contentType = reportContentType;
            }

            JRAbstractExporter exporter = null;
            String extension = null;
            
            if ("application/vnd.ms-excel".equals(contentType) || "application/msexcel".equals(contentType)) {
                exporter = new JRXlsExporter();
                extension = ".xls";
            } else if ("text/comma-separated-values".equals(contentType)) {
                exporter = new JRCsvExporter();
                extension = ".csv";
            } else if ("text/html".equals(contentType)) {
                exporter = new JRHtmlExporter();
            } else if ("text/rtf".equals(contentType)) {
                exporter = new JRRtfExporter();
                extension = ".rtf";
            } else {
                exporter = new JRPdfExporter();
                contentType = "application/pdf";
                extension = ".pdf";
            }

            if (extension != null && extension.length() > 0) {
                
            }
            response.setContentType(contentType);
            if (extension != null) {
                response.setHeader("Content-Disposition", "attachment; filename=" + name + extension);
            }
            exporter.setParameter(JRExporterParameter.JASPER_PRINT, jp);
            exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, response.getOutputStream());
            exporter.exportReport();
        } catch (IOException ie) {
            throw new ViewHandlerException("IO Error in report", ie);
        } catch (java.sql.SQLException e) {
            throw new ViewHandlerException("Database error while running report", e);
        } catch (Exception e) {
            throw new ViewHandlerException("Error in report", e);
            // } catch (ServletException se) {
            // throw new ViewHandlerException("Error in region", se.getRootCause());
        }
    }
}
