/******************************************************************************
 * 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.io.PrintWriter;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
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.compiere.model.MCurrency;
import org.compiere.model.MPaySelectionCheck;
import org.compiere.model.MPaySelectionLine;
import org.compiere.util.CLogger;
import org.compiere.util.DB;
import org.compiere.util.Env;
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: WPaymentExport.java,v 1.1 2010/01/13 11:51:47 clmg Exp $
 */
public class WPaymentExport extends HttpServlet {

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

	/**	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 Payment Export 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;
        }

        int paymentSelectionId = WebUtil.getParameterAsInt(request, "paymentSelectionId");
        String paymentRule = WebUtil.getParameter(request, "paymentRule");
        int documentNumber = WebUtil.getParameterAsInt(request, "documentNumber");
        
        response.setContentType("text/plain;charset=" + getCharSet(request.getLocale().getLanguage()));
        response.setHeader("Content-Disposition", "attachment; filename=PaymentExport.txt");
        response.setHeader("Content-Description", "File download for TXT.");

        //  get Checks
        MPaySelectionCheck [] checks = MPaySelectionCheck.get(
                paymentSelectionId, paymentRule, documentNumber, null);

        char x = '"';      //  ease
        StringBuffer line = null;
        PrintWriter fw = response.getWriter();

    //  write header
        line = new StringBuffer();
        line.append(x).append(Msg.translate(wsc.ctx, "Value")).append(x).append(",")
            .append(x).append(Msg.translate(wsc.ctx, "Name")).append(x).append(",")
            .append(x).append(Msg.translate(wsc.ctx, "Contact")).append(x).append(",")
            .append(x).append(Msg.translate(wsc.ctx, "Addr1")).append(x).append(",")
            .append(x).append(Msg.translate(wsc.ctx, "Addr2")).append(x).append(",")
            .append(x).append(Msg.translate(wsc.ctx, "City")).append(x).append(",")
            .append(x).append(Msg.translate(wsc.ctx, "State")).append(x).append(",")
            .append(x).append(Msg.translate(wsc.ctx, "ZIP")).append(x).append(",")
            .append(x).append(Msg.translate(wsc.ctx, "Country")).append(x).append(",")
            .append(x).append(Msg.translate(wsc.ctx, "ReferenceNo")).append(x).append(",")
            .append(x).append(Msg.translate(wsc.ctx, "DocumentNo")).append(x).append(",")
            .append(x).append(Msg.translate(wsc.ctx, "PayDate")).append(x).append(",")
            .append(x).append(Msg.translate(wsc.ctx, "Currency")).append(x).append(",")
            .append(x).append(Msg.translate(wsc.ctx, "PayAmount")).append(x).append(",")
            .append(x).append(Msg.translate(wsc.ctx, "Comment")).append(x)
            .append(Env.NL);
        fw.write(line.toString());

        //  write lines
        for (int i = 0; i < checks.length; i++)
        {
            MPaySelectionCheck mpp = checks[i];
            if (mpp == null)
                continue;
            //  BPartner Info
            String bp[] = getBPartnerInfo(mpp.getC_BPartner_ID());

            //  Comment - list of invoice document no
            StringBuffer comment = new StringBuffer();
            MPaySelectionLine[] psls = mpp.getPaySelectionLines(false);
            for (int l = 0; l < psls.length; l++)
            {
                if (l > 0)
                    comment.append(", ");
                comment.append(psls[l].getInvoice().getDocumentNo());
            }
            line = new StringBuffer();
            line.append(x).append(bp[0]).append(x).append(",")   // Value
                .append(x).append(bp[1]).append(x).append(",")    // Name
                .append(x).append(bp[2]).append(x).append(",") // Contact
                .append(x).append(bp[3]).append(x).append(",")   // Addr1
                .append(x).append(bp[4]).append(x).append(",")   // Addr2
                .append(x).append(bp[5]).append(x).append(",")    // City
                .append(x).append(bp[6]).append(x).append(",")  // State
                .append(x).append(bp[7]).append(x).append(",")  // ZIP
                .append(x).append(bp[8]).append(x).append(",") // Country
                .append(x).append(bp[9]).append(x).append(",")   // ReferenceNo
                //  Payment Info
                .append(x).append(mpp.getDocumentNo()).append(x).append(",")    // DocumentNo
                .append(mpp.getParent().getPayDate()).append(",")               // PayDate
                .append(x).append(MCurrency.getISO_Code(Env.getCtx(), mpp.getParent().getC_Currency_ID())).append(x).append(",")    // Currency
                .append(mpp.getPayAmt()).append(",")                // PayAmount
                .append(x).append(comment.toString()).append(x)     // Comment
                .append(Env.NL);
            fw.write(line.toString());
        }   //  write line

        fw.flush();
	}

    /**
     *  Get Customer/Vendor Info.
     *  Based on BP_ static variables
     *  @param C_BPartner_ID BPartner
     *  @return info array
     */
    private String[] getBPartnerInfo (int businessPartnerId) {
        String[] bp = new String[10];

        String sql = "SELECT bp.Value, bp.Name, c.Name AS Contact, "
            + "a.Address1, a.Address2, a.City, r.Name AS Region, a.Postal, "
            + "cc.Name AS Country, bp.ReferenceNo "
            + "FROM C_BPartner bp, AD_User c, C_BPartner_Location l, C_Location a, C_Region r, C_Country cc "
            + "WHERE bp.C_BPartner_ID=?"        // #1
            + " AND bp.C_BPartner_ID=c.C_BPartner_ID(+)"
            + " AND bp.C_BPartner_ID=l.C_BPartner_ID"
            + " AND l.C_Location_ID=a.C_Location_ID"
            + " AND a.C_Region_ID=r.C_Region_ID(+)"
            + " AND a.C_Country_ID=cc.C_Country_ID "
            + "ORDER BY l.IsBillTo DESC";
        try
        {
            PreparedStatement pstmt = DB.prepareStatement(sql, null);
            pstmt.setInt(1, businessPartnerId);
            ResultSet rs = pstmt.executeQuery();
            //
            if (rs.next())
            {
                bp[0] = rs.getString(1);
                if (bp[0] == null)
                    bp[0] = "";
                bp[1] = rs.getString(2);
                if (bp[1] == null)
                    bp[1] = "";
                bp[2] = rs.getString(3);
                if (bp[2] == null)
                    bp[2] = "";
                bp[3] = rs.getString(4);
                if (bp[3] == null)
                    bp[3] = "";
                bp[4] = rs.getString(5);
                if (bp[4] == null)
                    bp[4] = "";
                bp[5] = rs.getString(6);
                if (bp[5] == null)
                    bp[5] = "";
                bp[6] = rs.getString(7);
                if (bp[6] == null)
                    bp[6] = "";
                bp[7] = rs.getString(8);
                if (bp[7] == null)
                    bp[7] = "";
                bp[8] = rs.getString(9);
                if (bp[8] == null)
                    bp[8] = "";
                bp[9] = rs.getString(10);
                if (bp[9] == null)
                    bp[9] = "";
            }
            rs.close();
            pstmt.close();
        }
        catch (SQLException e)
        {
            log.log(Level.SEVERE, "getBPartnerInfo", e);
        }
        return bp;
    }   //  getBPartnerInfo

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