/**
 * 
 */
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 CreateFromInvoiceAction 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("closeCreateFromInvoice", "");
		CreateFromInvoiceForm createFromInvoiceForm = (CreateFromInvoiceForm)baseForm;
		HttpSession session = request.getSession();
		if (createFromInvoiceForm != null) {
			int windowNo = createFromInvoiceForm.getWindowNo();
			int operationType = createFromInvoiceForm.getOperation();
			int bpartnerId = createFromInvoiceForm.getBpartnerID();
			int processId = createFromInvoiceForm.getProcessId();
			String columnName = createFromInvoiceForm.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 = createFromInvoiceForm.getOrderSelected();
				String shipmentSel = createFromInvoiceForm.getShipmentSelected();
//				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;
				}
				//  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);
				createFromInvoiceForm.setBpartnerID(C_BPartner_ID);
				createFromInvoiceForm.setBpartnerName(lookup.getDisplay(new Integer(C_BPartner_ID)));
				createFromInvoiceForm.statInit(wsc.ctx);

				if (operationType == 2) {
					// Order selection
					createFromInvoiceForm.setOrderSelected(orderSel);
					createFromInvoiceForm.setShipmentSelected("0");
					List searchResult = createFromInvoiceForm.loadOrder(Integer.parseInt(orderSel), true, wsc.ctx, Integer.MAX_VALUE);
				    int rowCount = AmpiereUtil.setLargeRecordMsg(wsc.ctx, createFromInvoiceForm, searchResult.size());
					searchResult = createFromInvoiceForm.loadOrder(Integer.parseInt(orderSel), true, wsc.ctx, rowCount);
					session.setAttribute("createFromInvoiceResult", searchResult);
				} else if (operationType == 3) {
					// Shipment selection
					createFromInvoiceForm.setOrderSelected("0");
					createFromInvoiceForm.setShipmentSelected(shipmentSel);
					List searchResult = createFromInvoiceForm.loadShipment(Integer.parseInt(shipmentSel), wsc.ctx, Integer.MAX_VALUE);
				    int rowCount = AmpiereUtil.setLargeRecordMsg(wsc.ctx, createFromInvoiceForm, searchResult.size());
					searchResult = createFromInvoiceForm.loadShipment(Integer.parseInt(shipmentSel), wsc.ctx, rowCount);
					session.setAttribute("createFromInvoiceResult", searchResult);
				} else if (operationType == 4) {
					// Submit selection and close popup window
					createFromInvoiceForm.setOrderSelected(orderSel);
					createFromInvoiceForm.setShipmentSelected(shipmentSel);
					int C_Invoice_ID = ((Integer)ws.getCurTab().getValue("C_Invoice_ID")).intValue();
					List searchResult = (List)session.getAttribute("createFromInvoiceResult");
					if (createFromInvoiceForm.save(wsc.ctx, C_Invoice_ID, searchResult)) {
						ws.getCurTab().dataRefresh();
					}
					request.setAttribute("closeCreateFromInvoice", "close");
				} else {
					session.setAttribute("createFromInvoiceResult", null);
				}
				createFromInvoiceForm.setOperation(0);
		  	}
		}

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