package com.ampiere.web.struts.form;

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.MPaySelectionCheck;
import org.compiere.util.CLogger;
import org.compiere.util.Msg;
import org.compiere.util.WebSessionCtx;

import com.ampiere.util.Constants;

/**
 * @author siqinbilige
 */
public class PaymentPrintAction 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 = "PaymentPrintForm";

    /** 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);
        
        PaymentPrintForm myForm =
            (PaymentPrintForm) request.getAttribute(ACTION_FORM);

        String column = myForm.getChangedColumn();
        if (column.equals("paymentSelectionId")) {
            // Payment selection changed.
            actionForward = mapping.findForward(PAYMENT_LIST);
        } else if (column.equals("paymentRule")) {
            // Payment rule chenged.
            actionForward = mapping.findForward(PAYMENT_LIST);
        } else if (column.equals("export")) {
            // Export button clicked.
            export(wsc, myForm);
            actionForward = mapping.findForward(PAYMENT_LIST);
        } else if (column.equals("print")) {
            // Print button clicked
            actionForward = mapping.findForward(PAYMENT_LIST);
        } else if (column.equals("process")) {
            // process button clicked
            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"));
                
                generatePaySelect(wsc, myForm);

                actionForward = mapping.findForward(PAYMENT_LIST);
            } else {
                actionForward = mapping.findForward(PAYMENT_LIST);
            }
            */
            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;
    }
    
    /**
     *  Export payments to file.
     * @param wsc Context
     * @param form Action form
     */
    private void export(
            final WebSessionCtx wsc,
            final PaymentPrintForm form) {

        if (!getChecks(wsc, form)) {
            return;
        }

        StringBuffer sb = new StringBuffer();
        sb.append( "openHistoryWindow(" )
          .append( "\"" )
          .append( "/compiere/ampiere/WPaymentExport" )
          .append( "?paymentSelectionId=" + form.getPaymentSelectionId() )
          .append( "&paymentRule=" + form.getPaymentRule() )
          .append( "&documentNumber=" + form.getDocumentNumber() )
          .append( "\"," )
          .append( "\"WPaymentExport\" );" );

        form.setResultInfo(sb.toString());
    }   //  cmd_export

    /**
     *  Get Checks.
     * @param wsc Context
     * @param form Action form
     */
    private boolean getChecks(
            final WebSessionCtx wsc,
            final PaymentPrintForm form) {

        //  do we have values
        if ( form.getPaymentSelectionId() <= 0
                || form.getBankAccountId() <= 0
                || form.getPaymentRule().equals("")
                || form.getDocumentNumber() == 0)
        {
            form.setResultInfo("alert('"
                    + Msg.translate(wsc.ctx, "VPayPrintNoRecords")
                    + ":"
                    + Msg.translate(wsc.ctx, "C_PaySelectionLine_ID")
                    + " #0');");
            return false;
        }

        log.config("C_PaySelection_ID="
                + form.getPaymentSelectionId()
                + ", PaymentRule="
                + form.getPaymentRule()
                + ", DocumentNo="
                + form.getDocumentNumber());

        //  get Checks
        MPaySelectionCheck [] checks = MPaySelectionCheck.get(
                form.getPaymentSelectionId(),
                form.getPaymentRule(),
                form.getDocumentNumber(),
                null);

        if (checks == null || checks.length == 0)
        {
            form.setResultInfo("alert('"
                    + Msg.translate(wsc.ctx, "VPayPrintNoRecords")
                    + ":"
                    + Msg.translate(wsc.ctx, "C_PaySelectionLine_ID")
                    + " #0');");
            return false;
        }
        return true;
    }   //  getChecks
}
