/******************************************************************************
 * The contents of this file are subject to the   Compiere License  Version 1.1
 * ("License"); You may not use this file except in compliance with the License
 * You may obtain a copy of the License at http://www.compiere.org/license.html
 * Software distributed under the License is distributed on an  "AS IS"  basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
 * the specific language governing rights and limitations under the License.
 * The Original Code is Compiere ERP & CRM Smart Business Solution. The Initial
 * Developer of the Original Code is Jorg Janke. Portions created by Jorg Janke
 * are Copyright (C) 1999-2005 Jorg Janke.
 * All parts are Copyright (C) 1999-2005 ComPiere, Inc.  All Rights Reserved.
 * Contributor(s): ______________________________________.
 *****************************************************************************/
package com.ampiere.web.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.logging.Level;

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 org.compiere.model.MPInstance;
import org.compiere.model.MPaySelectionCheck;
import org.compiere.model.MProcess;
import org.compiere.framework.Query;
import org.compiere.framework.PrintInfo;
import org.compiere.print.MPrintFormat;
import org.compiere.print.ReportEngine;
import org.compiere.process.ProcessInfo;
import org.compiere.util.CLogger;
import org.compiere.util.Env;
import org.compiere.util.Language;
import org.compiere.util.Msg;
import org.compiere.util.WebEnv;
import org.compiere.util.WebSessionCtx;
import org.compiere.util.WebUtil;

/**
 *  Web Print Document Page.
 *  
 *  @author Siqin
 *  @version  $Id: WPrintReport.java,v 1.1 2010/01/13 11:51:47 clmg Exp $
 */
public class WPrintReport extends HttpServlet {

    /** Serial Version UID. */
	private static final long serialVersionUID = 9003001336699200370L;

    /** Read buffer size. */
    private static final int BUFFER_SIZE = 1024;

    /** Export max record size. */
    private static final int MAX_RECORD = 500;

	/**	Logger. */
    private CLogger log = CLogger.getCLogger(getClass());

    /** Report Engine. */
    private ReportEngine re;
    
    /**
	 *	Initialize.
	 *  @param config confif
	 *  @throws ServletException ServletException
	 */
	public final void init(final ServletConfig config) throws ServletException {
		super.init(config);
		if (!WebEnv.initWeb(config)) {
			throw new ServletException("WPrintWindow.init");
        }
	}	//	init

	/**
	 * Get Servlet information.
	 * @return servlet info
	 */
	public final String getServletInfo() {
		return "Ampiere Web Print Window";
	}

	/**
	 *	Clean up.
	 */
	public final void destroy() {
		log.info("destroy");
		super.destroy();
	}

	/**
	 *	Process the HTTP Get request - forward to Post.
	 *  @param request request
	 *  @param response response
	 *  @throws ServletException ServletException
	 *  @throws IOException IOException
	 */
	public final void doGet(final HttpServletRequest request, final HttpServletResponse response)
    throws ServletException, IOException {
		log.info("doGet");

		Language oldLogin = Language.getLoginLanguage();
		
		WebSessionCtx wsc = WebSessionCtx.get(request);
        if (wsc == null) {
            WebUtil.createTimeoutPage(request, response, this, null);
            return;
        }

        WWindowStatus ws = WWindowStatus.get(request);

		Language.setLoginLanguage(wsc.language);

//		MProcess process = MProcess.get(wsc.ctx, Env.getContextAsInt(wsc.ctx, "AD_Process_ID"));
		MProcess process = MProcess.get(wsc.ctx, wsc.ctx.getContextAsInt("AD_Process_ID"));
		
//		int pInstanceId = Env.getContextAsInt(wsc.ctx, "AD_PInstance_ID");
		int pInstanceId = wsc.ctx.getContextAsInt("AD_PInstance_ID");
		
		//	Create Process Instance
		MPInstance pInstance = new MPInstance(wsc.ctx, pInstanceId, null);
		//
		ProcessInfo processInfo = new ProcessInfo(process.getName(), process.getAD_Process_ID());
//		processInfo.setAD_User_ID(Env.getAD_User_ID(wsc.ctx));
//		processInfo.setAD_Client_ID(Env.getAD_Client_ID(wsc.ctx));
		processInfo.setAD_User_ID(wsc.ctx.getAD_User_ID());
		processInfo.setAD_Client_ID(wsc.ctx.getAD_Client_ID());
		processInfo.setAD_PInstance_ID(pInstance.getAD_PInstance_ID());
        processInfo.setRecord_ID(pInstance.getRecord_ID());
		if (ws != null) {
			processInfo.setRecord_ID(ws.curTab.getRecord_ID());
		}
		
		if (processInfo.getAD_Process_ID() == 110) {
            //  C_Order
            re = ReportEngine.get(wsc.ctx, ReportEngine.ORDER, processInfo.getRecord_ID());
        } else if (processInfo.getAD_Process_ID() == 116) {
            //  C_Invoice
            re = ReportEngine.get(wsc.ctx, ReportEngine.INVOICE, processInfo.getRecord_ID());
        } else if (processInfo.getAD_Process_ID() == 117) {
            //  M_InOut
            re = ReportEngine.get(wsc.ctx, ReportEngine.SHIPMENT, processInfo.getRecord_ID());
        } else if (processInfo.getAD_Process_ID() == 217) {
            //  C_Project
            re = ReportEngine.get(wsc.ctx, ReportEngine.PROJECT, processInfo.getRecord_ID());
        } else if (processInfo.getAD_Process_ID() == 276) {
            //  C_RfQResponse
            re = ReportEngine.get(wsc.ctx, ReportEngine.RFQ, processInfo.getRecord_ID());
        } else if (processInfo.getAD_Process_ID() == 313) {
            //  C_Payment
            int paySelectionCheckId = 0;
			MPaySelectionCheck psc = MPaySelectionCheck.getOfPayment(wsc.ctx, processInfo.getRecord_ID(), null);
			if (psc != null) {
                paySelectionCheckId = psc.getC_PaySelectionCheck_ID();
            } else {
				psc = MPaySelectionCheck.createForPayment(wsc.ctx, processInfo.getRecord_ID(), null);
				if (psc != null) {
                    paySelectionCheckId = psc.getC_PaySelectionCheck_ID();
                }
			}
			re = ReportEngine.get(wsc.ctx, ReportEngine.CHECK, paySelectionCheckId);
		} else if (processInfo.getAD_Process_ID() == 159) {
            //  Dunning
            re = ReportEngine.get(wsc.ctx, ReportEngine.DUNNING, processInfo.getRecord_ID());
        } else if (processInfo.getAD_Process_ID() == 202 //	Financial Report
			|| processInfo.getAD_Process_ID() == 204) {  //	Financial Statement
			//  Create Query from Parameters
			String tableName = processInfo.getAD_Process_ID() == 202 ? "T_Report" : "T_ReportStatement";
			Query query = Query.get(wsc.ctx, processInfo.getAD_PInstance_ID(), tableName);
			//	Get PrintFormat
			MPrintFormat format = (MPrintFormat) processInfo.getTransientObject();
			if (format == null) {
				format = (MPrintFormat) processInfo.getSerializableObject();
            }

            if (format == null) {
				log.log(Level.SEVERE, "startFinReport - No PrintFormat");
				return;
			}
			PrintInfo info = new PrintInfo(processInfo);

			re = new ReportEngine(wsc.ctx, format, query, info);
		} else {
			re = ReportEngine.get(wsc.ctx, processInfo);
		}

        int pfId = new Integer(request.getParameter("PrintFormat"));
        MPrintFormat printFormat = MPrintFormat.get(wsc.ctx, pfId, false);
        printFormat.setLanguage(re.getPrintFormat().getLanguage());
        printFormat.setTranslationLanguage(re.getPrintFormat().getLanguage());

        // 2006.08.23 SiqinBilige start
//        int currencyPrecision = re.getCurrencyPrecision();
        re = new ReportEngine(wsc.ctx, printFormat, re.getQuery(), re.getPrintInfo());
//        re.setCurrencyPrecision(currencyPrecision);
        re.setPrintData(re.getPrintData());
        // 2006.08.23 SiqinBilige end

		if (re.getRowCount() > MAX_RECORD) {
			WebUtil.createErrorPage(
					request,
					response,
					this, 
					Msg.getMsg(ws.ctx, "ParameterMissing")
					);
		} else {
            boolean result = makeDownloadFile(re, request, response, wsc.language);
            if (!result) {
                WebUtil.createErrorPage(
                        request,
                        response,
                        this, 
                        Msg.getMsg(ws.ctx,
                                "Can not create report !!!"));
            }
		}

		re = null;

		Language.setLoginLanguage(oldLogin);

	}

	/**
	 *	Process the HTTP Post request.
	 *
	 *  @param request request
	 *  @param response response
	 *  @throws ServletException ServletException
	 *  @throws IOException IOException
	 */
	public final void doPost(final HttpServletRequest request, final HttpServletResponse response) 
	throws ServletException, IOException {
		log.info("doPost");
	}

    /**
     * Make download file.
     * @param reportEngine report engine
     * @param request request
     * @param response response
     * @param language language
     * @return result
     */
    private boolean makeDownloadFile(
            final ReportEngine reportEngine,
            final HttpServletRequest request,
            final HttpServletResponse response,
            final Language language) {

        boolean result = true;

        try {
            if (request.getParameter("FileFormat").equals("ps")) {
                response.setContentType("application/postscript");
                // Jirimuto modified for Japanese name have problem on IE. 2009/04/07 
                // response.setHeader("Content-Disposition", "inline; filename=" + reportEngine.getName() + ".ps");
                response.setHeader("Content-Disposition", "inline; filename=" + reportEngine.getPrintFormat().get_ID() + ".ps");
                response.setHeader("Content-Description", "File download for PS.");
                File f = File.createTempFile("ReportEngine", ".ps");
                reportEngine.createPS(f);
                FileInputStream fis = new FileInputStream(f);
                ServletOutputStream ouputStream = response.getOutputStream();
                byte [] buf = new byte[BUFFER_SIZE];
                int len;
                while ((len = fis.read(buf)) != -1) {
                    ouputStream.write(buf, 0, len);
                }
                fis.close();
                f.delete();
                ouputStream.flush();
                ouputStream.close();
            } else if (request.getParameter("FileFormat").equals("pdf")) {
                response.setContentType("application/pdf");
                // Jirimuto modified for Japanese name have problem on IE. 2009/04/07 
                // response.setHeader("Content-Disposition", "inline; filename=" + reportEngine.getName() + ".pdf");
                response.setHeader("Content-Disposition", "inline; filename=" + reportEngine.getPrintFormat().get_ID() + ".pdf");
                response.setHeader("Content-Description", "File download for PDF.");
                ServletOutputStream ouputStream = response.getOutputStream();
                ouputStream.write(reportEngine.createPDFData());
                ouputStream.flush();
                ouputStream.close();
            } else {
                result = false;
            }
        } catch (IOException e) {
            log.log(Level.SEVERE, "ReportEngine", e);
            result = false;
        }

        return result;
    }
}
