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

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.model.MLookup;
import org.compiere.model.MLookupFactory;
import org.compiere.util.CLogger;
import org.compiere.util.DisplayType;
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 CreateFromShipmentAction 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("closeCreateFromShipment", "");
		CreateFromShipmentForm createFromShipmentForm = (CreateFromShipmentForm)baseForm;
		HttpSession session = request.getSession();
		if (createFromShipmentForm != null) {
			int windowNo = createFromShipmentForm.getWindowNo();
			int operationType = createFromShipmentForm.getOperation();
			int bpartnerId = createFromShipmentForm.getBpartnerID();
			int processId = createFromShipmentForm.getProcessId();
			String columnName = createFromShipmentForm.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 orderSel = createFromShipmentForm.getOrderSelected();
				String invoiceSel = createFromShipmentForm.getInvoiceSelected();
//				int C_BPartner_ID = Env.getContextAsInt(wsc.ctx, windowNo, "C_BPartner_ID");
				int C_BPartner_ID = wsc.ctx.getContextAsInt(windowNo, "C_BPartner_ID");
				if (bpartnerId > 0 && bpartnerId != C_BPartner_ID) {
					C_BPartner_ID = bpartnerId;
				}
				int M_InOut_ID = 0;
				if (((Integer)ws.getCurTab().getValue("M_InOut_ID")) != null) {
					M_InOut_ID = ((Integer)ws.getCurTab().getValue("M_InOut_ID")).intValue();
				}

				//  load BPartner
				int AD_Column_ID = 3499;        //  C_Invoice.C_BPartner_ID
//				MLookup lookup = MLookupFactory.get (wsc.ctx, windowNo, 0, AD_Column_ID, DisplayType.Search);
				MLookup lookup = MLookupFactory.get (wsc.ctx, windowNo, AD_Column_ID, DisplayType.Search);
				createFromShipmentForm.setBpartnerID(C_BPartner_ID);
				createFromShipmentForm.setBpartnerName(lookup.getDisplay(new Integer(C_BPartner_ID)));
				createFromShipmentForm.statInit(wsc.ctx);

				if (operationType == 2) {
					// Order selection
					createFromShipmentForm.setOrderSelected(orderSel);
					createFromShipmentForm.setShipmentSelected("0");
					createFromShipmentForm.setInvoiceSelected("0");
					List searchResult = createFromShipmentForm.loadOrder(Integer.parseInt(orderSel), false, wsc.ctx, Integer.MAX_VALUE);
				    int rowCount = AmpiereUtil.setLargeRecordMsg(wsc.ctx, createFromShipmentForm, searchResult.size());
					searchResult = createFromShipmentForm.loadOrder(Integer.parseInt(orderSel), false, wsc.ctx, rowCount);
					session.setAttribute("createFromShipmentResult", searchResult);
				} else if (operationType == 3) {
					// Shipment selection
					createFromShipmentForm.setOrderSelected("0");
					createFromShipmentForm.setShipmentSelected("0");
					createFromShipmentForm.setInvoiceSelected(invoiceSel);
					List searchResult = createFromShipmentForm.loadInvoice(Integer.parseInt(invoiceSel), wsc.ctx, Integer.MAX_VALUE);
				    int rowCount = AmpiereUtil.setLargeRecordMsg(wsc.ctx, createFromShipmentForm, searchResult.size());
					searchResult = createFromShipmentForm.loadInvoice(Integer.parseInt(invoiceSel), wsc.ctx, rowCount);
					session.setAttribute("createFromShipmentResult", searchResult);
				} else if (operationType == 4) {
					// Submit selection and close popup window
					createFromShipmentForm.setOrderSelected(orderSel);
					createFromShipmentForm.setInvoiceSelected(invoiceSel);
					List searchResult = (List)session.getAttribute("createFromShipmentResult");
					if (createFromShipmentForm.save(wsc.ctx, M_InOut_ID, searchResult)) {
						ws.getCurTab().dataRefresh();
					}
					request.setAttribute("closeCreateFromShipment", "close");
				} else {
					session.setAttribute("createFromShipmentResult", null);
				}
				createFromShipmentForm.setOperation(0);
		  	}
		}

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