package com.ampiere.web.struts.form;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.ParsePosition;
import java.util.Date;
import java.util.logging.Level;

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

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.compiere.model.MPaySelection;
import org.compiere.model.MPaySelectionLine;
import org.compiere.util.CLogger;
import org.compiere.util.Env;
import org.compiere.util.Msg;
import org.compiere.util.WebSessionCtx;

import com.ampiere.util.Constants;

/**
 * @author siqinbilige
 */
public class PaymentSelectionAction extends Action {

    /** Logger. */
    private CLogger log = CLogger.getCLogger(this.getClass());
    
    /** Order List Forward. */
    private static final String PAYMENT_LIST = "paymentlist";

    /** Action Form. */
    private static final String ACTION_FORM = "PaymentSelectionForm";

    /** Global Error Forward. */
    private static final String ERROR_FORWARD = "error";

    /**
     * Action execute.
     * @param mapping mapping
     * @param form form
     * @param request request
     * @param response response
     * @throws Exception Exception
     * @return ActionForward
     * @see org.apache.struts.action.Action#execute(
     *      org.apache.struts.action.ActionMapping,
     *      org.apache.struts.action.ActionForm,
     *      javax.servlet.http.HttpServletRequest,
     *      javax.servlet.http.HttpServletResponse)
     */
    public final ActionForward execute(
            final ActionMapping mapping,
            final ActionForm form,
            final HttpServletRequest request,
            final HttpServletResponse response)
    throws Exception {
    	
		//201001 
        WebSessionCtx wscTest = WebSessionCtx.get(request); 
        if (wscTest == null) {
            log.log(Level.SEVERE, "Session Time Out.");
            request.setAttribute(Constants.SESSION_TIMEOUT_INFO, "Session Time Out. Please login again.");
            return mapping.findForward(Constants.SESSION_TIMEOUT);
        }
        //--201001    	

        log.fine("Begin " + this.getClass().getName() + ";execute");

        WebSessionCtx wsc = WebSessionCtx.get(request); 
        if (wsc == null) {
            log.log(Level.SEVERE, "Session Time Out.");
            return mapping.findForward(ERROR_FORWARD);
        }

        ActionForward actionForward = mapping.findForward(PAYMENT_LIST);
        
        PaymentSelectionForm myForm =
            (PaymentSelectionForm) request.getAttribute(ACTION_FORM);

        String column = myForm.getChangedColumn();
        if (column.equals("bankAccount")) {
            // Bank Account selection changed.
            actionForward = mapping.findForward(PAYMENT_LIST);
        } else if (column.equals("businessPartner")) {
            // Business Partner ID chenged.
            actionForward = mapping.findForward(PAYMENT_LIST);
        } else if (column.equals("onlyDueInvoices")) {
            // Only Due Invoices chenged.
            actionForward = mapping.findForward(PAYMENT_LIST);
        } else if (column.equals("paymentDate")) {
            // Payment Date chenged.
            actionForward = mapping.findForward(PAYMENT_LIST);
        } else {
            // Genarate shipments.
            if (myForm.getInvoiceIdList() != null && myForm.getInvoiceIdList().length > 0) {
//                myForm.setMainWindowTitle(Env.getContext(wsc.ctx, "FormName") + " - " + wsc.loginInfo);
//                myForm.setPageTitle(Env.getContext(wsc.ctx, "FormName"));
                myForm.setMainWindowTitle(wsc.ctx.getContext("FormName") + " - " + wsc.loginInfo);
                myForm.setPageTitle(wsc.ctx.getContext("FormName"));
                
                generatePaySelect(wsc, myForm);

                actionForward = mapping.findForward(PAYMENT_LIST);
            } else {
                actionForward = mapping.findForward(PAYMENT_LIST);
            }
        }
        
        myForm.setChangedColumn(null);
        // Save form to request.
        request.setAttribute(ACTION_FORM, myForm);

        log.fine("End " + this.getClass().getName() + ";execute");

        return actionForward;
    }
    
    /**
     *  Generate PaySelection.
     * @param wsc Context
     * @param form Action form
     */
    private void generatePaySelect(final WebSessionCtx wsc, final PaymentSelectionForm form) {
        String trxName = null;

        String [] invoiceInfo = form.getInvoiceIdList();
        if (invoiceInfo == null || invoiceInfo.length == 0) {
            return;
        }

        //  Create Header
        MPaySelection paySelection = new MPaySelection(wsc.ctx, 0, trxName);
        paySelection.setName(Msg.getMsg(wsc.ctx, "VPaySelect") + " - " + form.getPaymentDate());
        Date payDate = wsc.dateFormat.parse(form.getPaymentDate(), new ParsePosition(0));
        paySelection.setPayDate(new Timestamp(payDate.getTime()));

        String [] bankInfo = form.getBankAccount().split("\\|");
        paySelection.setC_BankAccount_ID(Integer.valueOf(bankInfo[0]));
        paySelection.setIsApproved(true);
        if (!paySelection.save()) {
            form.setResultInfo("alert('" + Msg.translate(wsc.ctx, "SaveError")
                            +  " : "
                            +  Msg.translate(wsc.ctx, "C_PaySelection_ID") + "');");
            return;
        }
        log.config(paySelection.toString());

        //  Create Lines
        int rows = invoiceInfo.length;
        int line = 0;
        for (int i = 0; i < rows; i++) {
            line += 10;
            MPaySelectionLine psl = new MPaySelectionLine(paySelection, line, form.getPaymentRule());
            String [] invoice = invoiceInfo[i].split("\\|");
            int invoiceId = Integer.valueOf(invoice[0]);
            BigDecimal openAmount = new BigDecimal(invoice[1]);
            BigDecimal payAmount = new BigDecimal(invoice[2]);
            boolean isSOTrx = false;

            psl.setInvoice(invoiceId, isSOTrx, openAmount, payAmount, openAmount.subtract(payAmount));
            if (!psl.save(trxName)) {
                form.setResultInfo("alert('" + Msg.translate(wsc.ctx, "SaveError")
                                 + " : "
                                 + Msg.translate(wsc.ctx, "C_PaySelectionLine_ID") + "');");
                return;
            }
            log.fine("C_Invoice_ID=" + invoiceId + ", PayAmt=" + payAmount);
        }   //  for the selected rows

        //  Ask to Post it
        // if (!ADialog.ask(m_WindowNo, this, "VPaySelectGenerate?", "(" + m_ps.getName() + ")"))
        //    return;

        // Prepare Payment
        form.setResultInfo("startButton('C_PaySelection_CreatePayment', 0, 155, "
                + MPaySelection.Table_ID + ", "
                + paySelection.getC_PaySelection_ID() + ");");
    }   //  generatePaySelect

}
