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

import java.sql.Timestamp;
import java.util.List;
import java.util.logging.Level;

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

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

import com.ampiere.util.AmpiereUtil;
import com.ampiere.util.Constants;
import com.ampiere.web.servlet.WWindowStatus;
import com.ampiere.web.struts.common.PopupBaseAction;

/**
 * @author Shinjirito
 *
 */
public class CreateFromStatementAction 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   
		
		request.setAttribute("closeCreateFromStatement", "");
		CreateFromStatementForm createFromStatementForm = (CreateFromStatementForm)baseForm;
		HttpSession session = request.getSession();
		if (createFromStatementForm != null) {
			int windowNo = createFromStatementForm.getWindowNo();
			int operationType = createFromStatementForm.getOperation();
			int processId = createFromStatementForm.getProcessId();
			String columnName = createFromStatementForm.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");
				}

				String bankAccountSel = createFromStatementForm.getBankAccountSelected();
				Timestamp ts = (Timestamp)ws.getCurTab().getValue("StatementDate");
				createFromStatementForm.statInit(wsc.ctx, ts, Integer.MAX_VALUE);

				if (operationType == 2) {
					// Order selection
				} else if (operationType == 3) {
					// Bank account selection
					createFromStatementForm.setOrderSelected("0");
					createFromStatementForm.setShipmentSelected("0");
					createFromStatementForm.setInvoiceSelected("0");
					createFromStatementForm.setBankAccountSelected(bankAccountSel);
					List searchResult = createFromStatementForm.loadBankAccount(Integer.parseInt(bankAccountSel), wsc.ctx, ts, Integer.MAX_VALUE);
				    int rowCount = AmpiereUtil.setLargeRecordMsg(wsc.ctx, createFromStatementForm, searchResult.size());
					searchResult = createFromStatementForm.loadBankAccount(Integer.parseInt(bankAccountSel), wsc.ctx, ts, rowCount);
					session.setAttribute("createFromStatementResult", searchResult);
				} else if (operationType == 4) {
					// Submit selection and close popup window
					createFromStatementForm.setOrderSelected("0");
					createFromStatementForm.setInvoiceSelected("0");
					List searchResult = (List)session.getAttribute("createFromStatementResult");
					int C_BankStatement_ID = 0;
					if (ws.getCurTab().getValue("C_BankStatement_ID") != null) {
						C_BankStatement_ID = ((Integer)ws.getCurTab().getValue("C_BankStatement_ID")).intValue();
					}
					if (createFromStatementForm.save(wsc.ctx, C_BankStatement_ID, searchResult)) {
						ws.getCurTab().dataRefresh();
					}
					request.setAttribute("closeCreateFromStatement", "close");
				} else {
					session.setAttribute("createFromStatementResult", null);
				}
				createFromStatementForm.setOperation(0);
		  	}
		}

	    return mapping.findForward("success");
	}
}
