/******************************************************************************
 * 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.io.Writer;
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.GridField;
import org.compiere.framework.Query;
import org.compiere.framework.PrintInfo;
import org.compiere.print.MPrintFormat;
import org.compiere.print.ReportEngine;
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: WPrintWindow.java,v 1.1 2010/01/13 11:51:46 clmg Exp $
 */
public class WPrintWindow 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 final CLogger log = CLogger.getCLogger(getClass());
	
    /**
	 *	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");

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

        WWindowStatus ws = WWindowStatus.get(request);

		int tableId = ws.curTab.getAD_Table_ID();

        Query query = ws.getCurTab().getQuery().deepCopy();
        query.addRestriction(ws.getCurTab().getWhereClause());

        //	Link for detail records
		String queryColumn = ws.curTab.getLinkColumnName();

        //	Current row otherwise
//		if (queryColumn.length() == 0) {
//			queryColumn = ws.curTab.getKeyColumnName();
//        }

        //	Find display
		String infoName = null;
		String infoDisplay = null;
		for (int i = 0; i < ws.curTab.getFieldCount(); i++) {
			GridField field = ws.curTab.getField(i);
			if (field.isKey()) {
				infoName = field.getHeader();
            }

            if ((field.getColumnName().equals("Name")
                    || field.getColumnName().equals("DocumentNo"))
				&& field.getValue() != null) {
				infoDisplay = field.getValue().toString();
            }
			if (infoName != null && infoDisplay != null) {
                break;
            }
		}

        if (queryColumn.length() != 0) {
			Object value =
//				Env.getContext(
//						ws.ctx,
//						ws.mWindow.getWindowNo(),
//						ws.curTab.getTabNo(),
//						queryColumn);
				ws.ctx.getContext(
						ws.mWindow.getWindowNo(),
						ws.curTab.getTabNo(),
						queryColumn);

            query.addRestriction(
					queryColumn,
					Query.EQUAL,
					value,
					infoName,
					infoDisplay);
        }

		MPrintFormat printFormat = null;

        // if not exist create it.
        if (request.getParameter("PrintFormat").equals("")) {
            printFormat = MPrintFormat.createFromTable(ws.ctx, tableId);
        } else {
            int pfId = new Integer(request.getParameter("PrintFormat"));
            printFormat = MPrintFormat.get(wsc.ctx, pfId, false);
        }

        printFormat.setLanguage(wsc.language);
        printFormat.setTranslationLanguage(wsc.language);

		PrintInfo printInfo = 
		new PrintInfo(
			printFormat.getName(),
			printFormat.getAD_Table_ID(),
			ws.curTab.getRecord_ID());
		printInfo.setDescription(query.getInfo());

		ReportEngine re = new ReportEngine(wsc.ctx,
		                                   printFormat,
                                           query,
                                           printInfo);

        if (re.getRowCount() > MAX_RECORD) {
			WebUtil.createErrorPage(
					request,
					response,
					this, 
					Msg.getMsg(ws.ctx,
                            "Can not create report for over 500 records!!!"));
		} 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;
	}

	/**
	 *	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");
                response.setHeader("Content-Disposition", "inline; filename=" + reportEngine.getName() + ".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("xml")) {
                response.setContentType("application/xml;charset=UTF8");
                response.setHeader("Content-Disposition", "inline; filename=" + reportEngine.getName() + ".xml");
                response.setHeader("Content-Description", "File download for XML.");
                Writer writer = response.getWriter();
                reportEngine.createXML(writer);
                writer.flush();
                writer.close();
            } else if (request.getParameter("FileFormat").equals("pdf")) {
                response.setContentType("application/pdf");
                response.setHeader("Content-Disposition", "inline; filename=" + reportEngine.getName() + ".pdf");
                response.setHeader("Content-Description", "File download for PDF.");
                ServletOutputStream ouputStream = response.getOutputStream();
                ouputStream.write(reportEngine.createPDFData());
                ouputStream.flush();
                ouputStream.close();
            } else if (request.getParameter("FileFormat").equals("html")) {
                response.setContentType("text/html");
                response.setHeader("Content-Disposition", "inline; filename=" + reportEngine.getName() + ".html");
                response.setHeader("Content-Description", "File download for HTML.");
                Writer writer = response.getWriter();
                reportEngine.createHTML(writer, false, language);
                writer.flush();
                writer.close();
            } else if (request.getParameter("FileFormat").equals("txt")) {
                response.setContentType("text/plain;charset=" + getCharSet(request.getLocale().getLanguage()));
                response.setHeader("Content-Disposition", "inline; filename=" + reportEngine.getName() + ".txt");
                response.setHeader("Content-Description", "File download for TXT.");
                Writer writer = response.getWriter();
                reportEngine.createCSV(writer, '\t', language);
                writer.flush();
                writer.close();
            } else if (request.getParameter("FileFormat").equals("ssv")) {
                response.setContentType("text/plain;charset=" + getCharSet(request.getLocale().getLanguage()));
                response.setHeader("Content-Disposition", "inline; filename=" + reportEngine.getName() + ".ssv");
                response.setHeader("Content-Description", "File download for SSV.");
                Writer writer = response.getWriter();
                reportEngine.createCSV(writer, ';', language);
                writer.flush();
                writer.close();
            } else if (request.getParameter("FileFormat").equals("csv")) {
                response.setContentType("application/vnd.ms-excel;charset=" + getCharSet(request.getLocale().getLanguage()));
                response.setHeader("Content-Disposition", "inline; filename=" + reportEngine.getName() + ".csv");
                response.setHeader("Content-Description", "File download for CSV.");
                Writer writer = response.getWriter();
                reportEngine.createCSV(writer, ',', language);
                writer.flush();
                writer.close();
            } else {
                result = false;
            }
        } catch (IOException e) {
            log.log(Level.SEVERE, "ReportEngine", e);
            result = false;
        }

        return result;
    }
        /**
     * Get charset.
     * @param local local
     * @return charset
     */
    private String getCharSet(final String local) {

        String charset = "UTF8";

        if (local.equals("ar")) {
            charset = "ISO-8859-6";
        } else if (local.equals("be")) {
            charset = "ISO-8859-5";
        } else if (local.equals("bg")) {
            charset = "ISO-8859-5";
        } else if (local.equals("ca")) {
            charset = "ISO-8859-1";
        } else if (local.equals("cs")) {
            charset = "ISO-8859-2";
        } else if (local.equals("da")) {
            charset = "ISO-8859-1";
        } else if (local.equals("de")) {
            charset = "ISO-8859-1";
        } else if (local.equals("el")) {
            charset = "ISO-8859-7";
        } else if (local.equals("en")) {
            charset = "ISO-8859-1";
        } else if (local.equals("es")) {
            charset = "ISO-8859-1";
        } else if (local.equals("et")) {
            charset = "ISO-8859-1";
        } else if (local.equals("fi")) {
            charset = "ISO-8859-1";
        } else if (local.equals("fr")) {
            charset = "ISO-8859-1";
        } else if (local.equals("hr")) {
            charset = "ISO-8859-2";
        } else if (local.equals("hu")) {
            charset = "ISO-8859-2";
        } else if (local.equals("is")) {
            charset = "ISO-8859-1";
        } else if (local.equals("it")) {
            charset = "ISO-8859-1";
        } else if (local.equals("iw")) {
            charset = "ISO-8859-8";
        } else if (local.equals("ja")) {
            charset = "Shift_JIS";
        } else if (local.equals("ko")) {
            charset = "EUC-KR";
        } else if (local.equals("lt")) {
            charset = "ISO-8859-2";
        } else if (local.equals("lv")) {
            charset = "ISO-8859-2";
        } else if (local.equals("mk")) {
            charset = "ISO-8859-5";
        } else if (local.equals("nl")) {
            charset = "ISO-8859-1";
        } else if (local.equals("no")) {
            charset = "ISO-8859-1";
        } else if (local.equals("pl")) {
            charset = "ISO-8859-2";
        } else if (local.equals("pt")) {
            charset = "ISO-8859-1";
        } else if (local.equals("ro")) {
            charset = "ISO-8859-2";
        } else if (local.equals("ru")) {
            charset = "ISO-8859-5";
        } else if (local.equals("sh")) {
            charset = "ISO-8859-5";
        } else if (local.equals("sk")) {
            charset = "ISO-8859-2";
        } else if (local.equals("sl")) {
            charset = "ISO-8859-2";
        } else if (local.equals("sq")) {
            charset = "ISO-8859-2";
        } else if (local.equals("sr")) {
            charset = "ISO-8859-5";
        } else if (local.equals("sv")) {
            charset = "ISO-8859-1";
        } else if (local.equals("tr")) {
            charset = "ISO-8859-9";
        } else if (local.equals("uk")) {
            charset = "ISO-8859-5";
        } else if (local.equals("zh")) {
            charset = "GB2312";
        } else if (local.equals("zh_TW")) {
            charset = "Big5";
        } else {
            charset = "UTF8";
        }

        return charset;
    }
}
