/******************************************************************************
 * 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.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.ecs.AlignType;
import org.apache.ecs.xhtml.form;
import org.apache.ecs.xhtml.input;
import org.apache.ecs.xhtml.option;
import org.apache.ecs.xhtml.script;
import org.apache.ecs.xhtml.select;
import org.apache.ecs.xhtml.table;
import org.apache.ecs.xhtml.td;
import org.apache.ecs.xhtml.tr;
import org.compiere.model.MRole;
import org.compiere.util.CLogger;
import org.compiere.util.DB;
import org.compiere.util.Msg;
import org.compiere.util.WebDoc;
import org.compiere.util.WebEnv;
import org.compiere.util.WebSessionCtx;
import org.compiere.util.WebUtil;

import com.ampiere.util.AmpiereUtil;

/**
 * Web Print Document Page.
 * @author Siqin
 * @version  $Id: WReport.java,v 1.1 2010/01/13 11:51:48 clmg Exp $
 */
public class WReport extends HttpServlet {
    /** Serial Version UID. */
    private static final long serialVersionUID = -66341541642842506L;
    /** Logger. */
    private 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 Report 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");

        //  Get Session attributes
        WebSessionCtx wsc = WebSessionCtx.get(request);
        if (wsc == null) {
            WebUtil.createTimeoutPage(request, response, this, null);
            return;
        }
        
        //  Get Parameter: Menu_ID
        int tableId = 0;
        WWindowStatus ws = WWindowStatus.get(request);
        if (ws != null)         {
            tableId = ws.curTab.getAD_Table_ID();
        }
        
//        String title = Msg.getMsg(wsc.ctx , "Report")
        String title = "レポート" //clmg 2009/03/06
                     + ": " + Msg.getElement(
                             wsc.ctx , ws.getCurTab().getKeyColumnName());

        WebDoc doc = WebDoc.createWindow(title);

        //  Set Title of main window
        doc.getBody().addElement(
                new script("top.document.title='" + title + "';"));

        // For date picker
        AmpiereUtil.addDatePicker(doc.getHead(), wsc);

        td center = doc.addWindowCenter(false);

        form myForm = new form("WReport").setName("WReport");
        table myTable = new table("0", "0", "5", "100%", null);
        myTable.setID("WReport");

        tr line;
        // Print format
        line = new tr();
        // Print format label
        line.addElement(new td().addElement(
                Msg.translate(wsc.ctx, "AD_PrintFormat_ID"))
                .setAlign(AlignType.RIGHT));
        // Print format selection
        ArrayList < String > ids = new ArrayList < String > ();
        ArrayList < String > names = new ArrayList < String > ();
        String sql = MRole.getDefault().addAccessSQL(
                "SELECT AD_PrintFormat_ID, Name, AD_Client_ID "
                    + "FROM AD_PrintFormat "
                    + "WHERE AD_Table_ID=? AND IsTableBased='Y' "
                    + "ORDER BY AD_Client_ID DESC, IsDefault DESC, Name",
                "AD_PrintFormat", MRole.SQL_NOTQUALIFIED, MRole.SQL_RO);
        try {
            PreparedStatement pstmt = DB.prepareStatement(sql, null);
            pstmt.setInt(1, tableId);
            ResultSet rs = pstmt.executeQuery();

            while (rs.next()) {
                ids.add(rs.getString(1));
                names.add(rs.getString(2));
            }
            rs.close();
            pstmt.close();
        } catch (SQLException e) {
            log.log(Level.SEVERE, sql, e);
        }
        
        option [] options = new option[ids.size()];
        for (int i = 0; i < ids.size(); i++) {
            options[i] = new option(ids.get(i)).addElement(names.get(i));
        }
        line.addElement(
                new td().addElement(
                new select("PrintFormat", options)
                .setID("PrintFormat")));
        myTable.addElement(line);

        // Export file type
        line = new tr();
        // File format label
        line.addElement(new td().addElement(
                Msg.translate(wsc.ctx, "Export"))
                .setAlign(AlignType.RIGHT));
        // File format selections
        options = new option[7];
        options[0] = new option("ps")
                        .addElement(Msg.getMsg(wsc.ctx, "FilePS"));
        options[1] = new option("xml")
                        .addElement(Msg.getMsg(wsc.ctx, "FileXML"));
        options[2] = new option("pdf")
                        .addElement(Msg.getMsg(wsc.ctx, "FilePDF"));
        options[2].setSelected(true);
        options[3] = new option("html")
                        .addElement(Msg.getMsg(wsc.ctx, "FileHTML"));
        options[4] = new option("txt")
                        .addElement(Msg.getMsg(wsc.ctx, "FileTXT"));
        options[5] = new option("ssv")
                        .addElement(Msg.getMsg(wsc.ctx, "FileSSV"));
        options[6] = new option("csv")
                        .addElement(Msg.getMsg(wsc.ctx, "FileCSV"));
        line.addElement(
                new td().addElement(
                new select("FileFormat", options)
                .setID("FileFormat")));
        myTable.addElement(line);

        // Submit botton
        line = new tr();
        line.addElement(new td(WebEnv.NBSP).setColSpan(2));
        myTable.addElement(line);

        // Submit botton
        line = new tr();
        input bt = new input(
                input.TYPE_BUTTON,
                "Export",
                Msg.translate(wsc.ctx, "Start"));
        StringBuffer sb = new StringBuffer();
        sb.append("openPrintWindow('/compiere/ampiere/WPrintWindow");
        sb.append("?PrintFormat='+document.WReport.PrintFormat.value+");
        sb.append("'&FileFormat='+document.WReport.FileFormat.value");
        sb.append(",'' );");
        bt.setOnClick(sb.toString());
        line.addElement(
                new td(null, AlignType.CENTER, AlignType.MIDDLE, false, bt)
                .setColSpan(2));
        //  Submit
        myTable.addElement(line);
        myForm.addElement(myTable);
        center.addElement(myForm);

        // Add body onUnload event, close all popup window when unload 
        doc.getBody().setOnUnload("closeMyChildren();");

        //
        WebUtil.createResponse(request, response, this, null, doc, true);
    }

    /**
     *    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");
    }

}
