/**
 * 
 */
package com.ampiere.web.struts.button;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.logging.Level;

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

import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.compiere.model.MRole;
import org.compiere.process.DocAction;
import org.compiere.report.core.RColumn;
import org.compiere.report.core.RModel;
import org.compiere.util.CLogger;
import org.compiere.util.DisplayType;
import org.compiere.util.Env;
import org.compiere.util.Msg;
import org.compiere.util.WebDoc;
import org.compiere.util.WebSessionCtx;

import com.ampiere.acct.AccountViewerData;
import com.ampiere.acct.Post;
import com.ampiere.grid.ed.WDocAction;
import com.ampiere.util.Constants;
import com.ampiere.web.servlet.WWindowStatus;
import com.ampiere.web.struts.common.PopupBaseAction;

/**
 * @author Shinjirito
 *
 */
public class ButtonAction extends PopupBaseAction {

    /**	Logger			*/
	protected CLogger	log = CLogger.getCLogger(this.getClass());

	/** (non-Javadoc)
	 * @see com.jware.base.web.struts.jWareBaseAction#doExecute(org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, org.apache.struts.action.ActionErrors, boolean)
	 */
	public ActionForward doExecute(ActionMapping mapping, ActionForm baseForm,
			HttpServletRequest request, HttpServletResponse response,
			ActionErrors errors, boolean mochaFlag) 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   
		
		String forward = "general";
		ButtonActionForm buttonActionForm = (ButtonActionForm)baseForm;
		if (buttonActionForm != null) {
			int windowNo = buttonActionForm.getWindowNo();
			int processId = buttonActionForm.getProcessId();
			String columnName = buttonActionForm.getColumnName();
		  	WebSessionCtx wsc = WebSessionCtx.get(request);
			WWindowStatus ws = WWindowStatus.get(request);
		  	if (wsc != null && columnName != null && ws != null) {
				//	Record_ID
				int record_ID = ws.getCurTab().getRecord_ID();
				//	Record_ID - Language Handling
				if (record_ID == -1 && ws.getCurTab().getKeyColumnName().equals("AD_Language"))
//					record_ID = Env.getContextAsInt (wsc.ctx, windowNo, "AD_Language_ID");
					record_ID = wsc.ctx.getContextAsInt (windowNo, "AD_Language_ID");
				//	Record_ID - Change Log ID
				if (record_ID == -1 && (processId == 306 || processId == 307))
				{
					Integer id = (Integer)ws.getCurTab().getValue("AD_ChangeLog_ID");
					record_ID = id.intValue();
				}
				//	Ensure it's saved
				if (record_ID == -1 && ws.getCurTab().getKeyColumnName().endsWith("_ID"))
				{
					request.setAttribute("ErrorTitle", Msg.translate(wsc.ctx, "Error"));
					request.setAttribute("ErrorMessage", Msg.translate(wsc.ctx, "SaveErrorRowNotFound"));
				    return mapping.findForward("error");
				}

				buttonActionForm.statInit(wsc.ctx);
				buttonActionForm.setTitle(Msg.translate(wsc.ctx, Msg.translate(wsc.ctx, columnName)));

				//	Pop up Payment Rules
				if (columnName.equals("PaymentRule"))
				{
//					WPayment vp = new WPayment(m_curWindowNo, m_curTab, vButton);
					forward = columnName.toLowerCase();
				}	//	PaymentRule

				//	Pop up Document Action (Workflow)
				else if (columnName.equals("DocAction"))
				{
					request.setAttribute("wDocAction", new WDocAction(windowNo, ws.getCurTab(), record_ID, wsc.ctx));
					forward = columnName.toLowerCase();
				}	//	DocAction

				//  Pop up Create From
				else if (columnName.equals("CreateFrom"))
				{
					//  m_curWindowNo
//					VCreateFrom vcf = VCreateFrom.create (m_curTab);
					forward = columnName.toLowerCase();
				}	//	CreateFrom

				//  Posting -----
				else if (columnName.equals("Posted") && MRole.getDefault().isShowAcct())
				{
                    //  Check Doc Status 
//					String processed = Env.getContext(wsc.ctx, windowNo, "Processed");
					String processed = wsc.ctx.getContext(windowNo, "Processed");

					if (!processed.equals("Y")) {
//						String docStatus = Env.getContext(wsc.ctx, windowNo, "DocStatus");
						String docStatus = wsc.ctx.getContext(windowNo, "DocStatus");
						if (DocAction.STATUS_Completed.equals(docStatus)
							|| DocAction.STATUS_Closed.equals(docStatus)
							|| DocAction.STATUS_Reversed.equals(docStatus)
							|| DocAction.STATUS_Voided.equals(docStatus)) {
                            ;
                        } else {
                            buttonActionForm.setError(true);
                            buttonActionForm.setMessage(Msg.translate(wsc.ctx, "PostDocNotComplete"));
                            buttonActionForm.setDataList(null);
						}
					}

                    //  Check Post Status
                    Object ps = ws.getCurTab().getValue("Posted");
                    if (ps != null && ps.equals("Y")) {
                        buttonActionForm.setTitle(Msg.getMsg(wsc.ctx, "AcctViewer"));
//                        int clientId = Env.getContextAsInt (ws.ctx, windowNo, "AD_Client_ID");
                        int clientId = ws.ctx.getContextAsInt (windowNo, "AD_Client_ID");
                        int tableId = ws.getCurTab().getAD_Table_ID();
                        log.info("AD_Table_ID=" + tableId + ", Record_ID=" + record_ID);
                        AccountViewerData accountViewerData = new AccountViewerData (ws.ctx, windowNo, clientId, tableId);
                        accountViewerData.AD_Table_ID = tableId;
                        accountViewerData.Record_ID = record_ID;

                        //  Parameter Info
                        StringBuffer para = new StringBuffer();

                        // Account Schema ID
//                        accountViewerData.C_AcctSchema_ID = Env.getContextAsInt (ws.ctx, "$C_AcctSchema_ID");
                        accountViewerData.C_AcctSchema_ID = ws.ctx.getContextAsInt ("$C_AcctSchema_ID");
                        para.append("C_AcctSchema_ID=").append(accountViewerData.C_AcctSchema_ID);
                        
                        // Organization 
                        // accountViewerData.AD_Org_ID = Env.getContextAsInt (ws.ctx, "#AD_Org_ID");
                        accountViewerData.AD_Org_ID = 0;

                        // Posting Type
                        accountViewerData.PostingType = "";
                        para.append(", PostingType=").append(accountViewerData.PostingType);

                        //  Document
                        accountViewerData.documentQuery = true;
                        para.append(", DocumentQuery=").append(accountViewerData.documentQuery);

                        para.append(", AD_Table_ID=").append(accountViewerData.AD_Table_ID)
                            .append(", Record_ID=").append(accountViewerData.Record_ID);

                        // Save Display Choices
                        accountViewerData.displayQty = false;
                        para.append(" - Display Qty=").append(accountViewerData.displayQty);
                        accountViewerData.displaySourceAmt = false;
                        para.append(", Source=").append(accountViewerData.displaySourceAmt);
                        accountViewerData.displayDocumentInfo = false;
                        para.append(", Doc=").append(accountViewerData.displayDocumentInfo);
                        // Sort
                        accountViewerData.sortBy1 = "";
                        accountViewerData.group1 = false;
                        para.append(" - Sorting: ").append(accountViewerData.sortBy1).append("/").append(accountViewerData.group1);
                        accountViewerData.sortBy2 = "";
                        accountViewerData.group2 = false;
                        para.append(", ").append(accountViewerData.sortBy2).append("/").append(accountViewerData.group2);
                        accountViewerData.sortBy3 = "";
                        accountViewerData.group3 = false;
                        para.append(", ").append(accountViewerData.sortBy3).append("/").append(accountViewerData.group3);
                        accountViewerData.sortBy4 = "";
                        accountViewerData.group4 = false;
                        para.append(", ").append(accountViewerData.sortBy4).append("/").append(accountViewerData.group4);

                        log.config(para.toString());

                        Thread.yield();

                        RModel table = accountViewerData.query();
                        
                        ArrayList < HashMap > dataList = new ArrayList < HashMap > ();

                        // Header
                        HashMap < String, String > row = new HashMap < String, String > ();
                        row.put("RowType", "title");
                        int columnCount = table.getColumnCount();
                        for ( int j = 0; j < columnCount; j++ ) {
                            RColumn col = table.getRColumn(j);
                            row.put("column"+j, col.getColHeader());
                        }
                        dataList.add(row);

                        // Data
                        int rowCount = table.getRowCount();
                        for ( int i = 0; i < rowCount; i++ ) {
                            row =  new HashMap < String, String > ();
                            // Row Type
                            if ((i % 2) == 0) {
                                row.put("RowType", "even");
                            } else {
                                row.put("RowType", "odd");
                            }
                            if ( i == rowCount - 1) {
                                row.put("RowType", "title");
                            }
                            for ( int j = 0; j < columnCount; j++ ) {
                                RColumn col = table.getRColumn(j);
                                String value = WebDoc.NBSP;
                                int displayType = col.getDisplayType();
                                Object data = table.getValueAt(i,j);
                                if ( data != null ) {
                                    if (DisplayType.isDate(displayType)) {
                                        if (displayType == DisplayType.DateTime) {
                                            value = wsc.dateTimeFormat.format(data); 
                                        } else {
                                            value = wsc.dateFormat.format(data);
                                        }
                                    } else if (DisplayType.isNumeric(displayType)) {
                                        if (displayType == DisplayType.Amount) {
                                            value = wsc.amountFormat.format(data);
                                        } else if (displayType == DisplayType.Number) {
                                            value = wsc.numberFormat.format(data);
//                                        } else if (displayType == DisplayType.CostPrice) {
//                                            value = wsc.costPriceFormat.format(data);
                                        } else if (displayType == DisplayType.Quantity) {
                                            value = wsc.quantityFormat.format(data);
                                        } else if (displayType == DisplayType.Integer) {
                                            value = wsc.integerFormat.format(data);
                                        } else {
                                            value = data.toString();
                                        }
                                    } else {
                                        value = data.toString();
                                    }
                                }
                                row.put("column" + j, value);
                            }
                            dataList.add(row);
                            buttonActionForm.setError(false);
                            buttonActionForm.setMessage("");
                            buttonActionForm.setDataList(dataList);
                        }
                    } else {
//                        String error = Post.postImmediate (
//                                wsc.ctx,
//                                Env.getAD_Client_ID(wsc.ctx),
//                                ws.getCurTab().getAD_Table_ID(),
//                                ws.getCurTab().getRecord_ID(),
//                                false );
                        String error = Post.postImmediate (
                                wsc.ctx,
                                wsc.ctx.getAD_Client_ID(),
                                ws.getCurTab().getAD_Table_ID(),
                                ws.getCurTab().getRecord_ID(),
                                false );

                        ws.getCurTab().dataRefresh();

                        if (error != null) {
                            buttonActionForm.setError(true);
                            buttonActionForm.setMessage(Msg.translate(wsc.ctx, "PostingError-N") + "<BR>" + Msg.translate(wsc.ctx, error));
                            buttonActionForm.setDataList(null);
                        } else {
                            buttonActionForm.setError(false);
                            buttonActionForm.setMessage(Msg.translate(wsc.ctx, "Success"));
                            buttonActionForm.setDataList(null);
                        }
                    }

                    forward = columnName.toLowerCase();
				}   //  Posted
		  	}
		}

	    return mapping.findForward(forward);
	}
}
