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

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.ActionMapping;
import org.compiere.model.MRole;
import org.compiere.util.Ctx;
import org.compiere.util.DB;
import org.compiere.util.Env;
import org.compiere.util.Msg;

import com.ampiere.dto.CodeValue;
import com.ampiere.web.struts.common.PopupBaseForm;

/**
 * @author Shinjirito
 *
 */
public class InfoProductForm extends PopupBaseForm {
	private static final long serialVersionUID = -2979814699715706579L;
	private String name;
	private String nameLabel;
	private String upc;
	private String upcLabel;
	private String sku;
	private String skuLabel;
	private String warehouse;
	private String warehouseLabel;
	private String priceListVersion;
	private String priceListVersionLabel;
	private String paSearchFlag = "false";
	private String paSearchWhere = "";
	private ArrayList<CodeValue> warehouseList = new ArrayList<CodeValue>();
	private ArrayList<CodeValue> priceList = new ArrayList<CodeValue>();

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getNameLabel() {
		return nameLabel;
	}

	public void setNameLabel(String nameLabel) {
		this.nameLabel = nameLabel;
	}

	public String getPriceListVersion() {
		return priceListVersion;
	}

	public void setPriceListVersion(String priceListVersion) {
		this.priceListVersion = priceListVersion;
	}

	public String getPriceListVersionLabel() {
		return priceListVersionLabel;
	}

	public void setPriceListVersionLabel(String priceListVersionLabel) {
		this.priceListVersionLabel = priceListVersionLabel;
	}

	public String getSku() {
		return sku;
	}

	public void setSku(String sku) {
		this.sku = sku;
	}

	public String getSkuLabel() {
		return skuLabel;
	}

	public void setSkuLabel(String skuLabel) {
		this.skuLabel = skuLabel;
	}

	public String getUpc() {
		return upc;
	}

	public void setUpc(String upc) {
		this.upc = upc;
	}

	public String getUpcLabel() {
		return upcLabel;
	}

	public void setUpcLabel(String upcLabel) {
		this.upcLabel = upcLabel;
	}

	public String getWarehouse() {
		return warehouse;
	}

	public void setWarehouse(String warehouse) {
		this.warehouse = warehouse;
	}

	public String getWarehouseLabel() {
		return warehouseLabel;
	}

	public void setWarehouseLabel(String warehouseLabel) {
		this.warehouseLabel = warehouseLabel;
	}

	public String getPaSearchWhere() {
		return paSearchWhere;
	}

	public void setPaSearchWhere(String paSearchWhere) {
		this.paSearchWhere = paSearchWhere;
	}

	public String getPaSearchFlag() {
		return paSearchFlag;
	}

	public void setPaSearchFlag(String paSearchFlag) {
		this.paSearchFlag = paSearchFlag;
	}

	/**
	 * Reset all properties to their default values.
	 *
	 * @param mapping The mapping used to select this instance
	 * @param request The servlet request we are processing
	 */
	public void reset(ActionMapping mapping, HttpServletRequest request) {
		/**
    	 * This will set LoginUserId From Session  
    	 */
    	super.reset(mapping, request);		
	}

	/**
	 *	Static Setup - set field value
	 */
	public void statInit(Ctx ctx) {
		super.statInit(ctx);
		setTitle(Msg.translate(ctx, "InfoProduct"));

		setValueLabel(Msg.translate(ctx, "Value"));
		setNameLabel(Msg.translate(ctx, "Name"));
		setUpcLabel(Msg.translate(ctx, "UPC"));
		setSkuLabel(Msg.translate(ctx, "SKU"));
		setWarehouseLabel(Msg.translate(ctx, "Warehouse"));
		setPriceListVersionLabel(Msg.translate(ctx, "PriceListVersion"));
	}

	/**
	 *	Dynamic Init
	 *  @param bpName BPartner name
	 *  @param whereClause where clause
	 */
	public void initInfo(String value, int M_PriceList_ID, int M_Warehouse_ID, Ctx ctx, int windowNo)
	{
		getDataLists(M_PriceList_ID);

		int M_PriceList_Version_ID = findPLV (M_PriceList_ID, ctx, windowNo);

		//	Set Value or Name
		if (value.startsWith("@") && value.endsWith("@")) {
			name = value.substring(1,value.length()-1);
		} else {
			setValue(value);
		}

		//	Set Warehouse
		if (M_Warehouse_ID == 0) {
//			M_Warehouse_ID = Env.getContextAsInt(ctx, "#M_Warehouse_ID");
			M_Warehouse_ID = ctx.getContextAsInt("#M_Warehouse_ID");
		}
		if (M_Warehouse_ID != 0) {
			setWarehouse (Integer.toString(M_Warehouse_ID));
		}

		// 	Set PriceList Version
		if (M_PriceList_Version_ID != 0) {
			setPriceListVersion (Integer.toString(M_PriceList_Version_ID));
		}
	}	//	initInfo

	/**
	 *	Get warehouse list and price list
	 *
	 * @param M_PriceList_ID price list
	 */
	private void getDataLists(int M_PriceList_ID)
	{
		warehouseList.clear();
		priceList.clear();

		//	Price List
		String SQL = "SELECT M_PriceList_Version.M_PriceList_Version_ID,"
			+ " M_PriceList_Version.Name || ' (' || c.Iso_Code || ')' AS ValueName "
			+ "FROM M_PriceList_Version, M_PriceList pl, C_Currency c "
			+ "WHERE M_PriceList_Version.M_PriceList_ID=pl.M_PriceList_ID"
			+ " AND pl.C_Currency_ID=c.C_Currency_ID"
			+ " AND M_PriceList_Version.IsActive='Y' AND pl.IsActive='Y'";
		//	Same PL currency as original one
		if (M_PriceList_ID != 0) {
			SQL += " AND EXISTS (SELECT * FROM M_PriceList xp WHERE xp.M_PriceList_ID=" + M_PriceList_ID
				+ " AND pl.C_Currency_ID=xp.C_Currency_ID)";
		}

		//	Add Access & Order
		SQL = MRole.getDefault().addAccessSQL (SQL, "M_PriceList_Version", true, false)	// fully qualidfied - RO 
					+ " ORDER BY M_PriceList_Version.Name";
		try
		{
			priceList.add(new CodeValue("0", ""));
			PreparedStatement pstmt = DB.prepareStatement(SQL, null);
			ResultSet rs = pstmt.executeQuery();
			while (rs.next())
			{
				priceList.add(new CodeValue(rs.getString(1), rs.getString(2)));
			}
			rs.close();
			pstmt.close();

			//	Warehouse
			SQL = MRole.getDefault().addAccessSQL (
				"SELECT M_Warehouse_ID, Value || ' - ' || Name AS ValueName "
				+ "FROM M_Warehouse "
				+ "WHERE IsActive='Y'",
					"M_Warehouse", MRole.SQL_NOTQUALIFIED, MRole.SQL_RO)
				+ " ORDER BY Value";
			warehouseList.add(new CodeValue("0", ""));
			pstmt = DB.prepareStatement(SQL, null);
			rs = pstmt.executeQuery();
			while (rs.next())
			{
				warehouseList.add(new CodeValue(rs.getString("M_Warehouse_ID"), rs.getString("ValueName")));
			}
			rs.close();
			pstmt.close();
		}
		catch (SQLException e)
		{
			e.printStackTrace();
		}
	}	//	fillPicks

	/**
	 *	Find Price List Version and update context
	 *
	 * @param M_PriceList_ID price list
	 * @return M_PriceList_Version_ID price list version
	 */
	private int findPLV (int M_PriceList_ID, Ctx ctx, int windowNo)
	{
		Timestamp priceDate = null;

		//	Sales Order Date
//		String dateStr = Env.getContext(ctx, windowNo, "DateOrdered"); 
		String dateStr = ctx.getContext(windowNo, "DateOrdered"); 
		if (dateStr != null && dateStr.length() > 0)
//			priceDate = Env.getContextAsDate(ctx, windowNo, "DateOrdered");
			priceDate = new Timestamp(ctx.getContextAsTime(windowNo, "DateOrdered"));
		else	//	Invoice Date
		{
//			dateStr = Env.getContext(ctx, windowNo, "DateInvoiced");
			dateStr = ctx.getContext(windowNo, "DateInvoiced");
			if (dateStr != null && dateStr.length() > 0)
//				priceDate = Env.getContextAsDate(ctx, windowNo, "DateInvoiced");
				priceDate = new Timestamp(ctx.getContextAsTime(windowNo, "DateInvoiced"));
		}

		//	Today
		if (priceDate == null) { 
			priceDate = new Timestamp(System.currentTimeMillis());
		}

		//
		int retValue = 0;
		String sql = "SELECT plv.M_PriceList_Version_ID, plv.ValidFrom "
			+ "FROM M_PriceList pl, M_PriceList_Version plv "
			+ "WHERE pl.M_PriceList_ID=plv.M_PriceList_ID"
			+ " AND plv.IsActive='Y'"
			+ " AND pl.M_PriceList_ID=? "					//	1
			+ "ORDER BY plv.ValidFrom DESC";
		//	find newest one
		try
		{
			PreparedStatement pstmt = DB.prepareStatement(sql, null);
			pstmt.setInt(1, M_PriceList_ID);
			ResultSet rs = pstmt.executeQuery();
			while (rs.next() && retValue == 0)
			{
				Timestamp plDate = rs.getTimestamp(2);
				if (!priceDate.before(plDate)) {
					retValue = rs.getInt(1);
				}
			}
			rs.close();
			pstmt.close();
		}
		catch (SQLException e)
		{
			e.printStackTrace();
		}
//		Env.setContext(ctx, windowNo, "M_PriceList_Version_ID", retValue);
		ctx.setContext(windowNo, "M_PriceList_Version_ID", retValue);
		return retValue;
	}	//	findPLV

	public ArrayList<CodeValue> getPriceList() {
		return priceList;
	}

	public ArrayList<CodeValue> getWarehouseList() {
		return warehouseList;
	}
}
