/******************************************************************************
 * The contents of this file are subject to the   Compiere License  Version 1.1
 * ("License"); You may not use this file except in compliance with the License
 * You may obtain a copy of the License at http://www.compiere.org/license.html
 * Software distributed under the License is distributed on an  "AS IS"  basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
 * the specific language governing rights and limitations under the License.
 * The Original Code is Compiere ERP & CRM Smart Business Solution. The Initial
 * Developer of the Original Code is Jorg Janke. Portions created by Jorg Janke
 * are Copyright (C) 1999-2005 Jorg Janke.
 * All parts are Copyright (C) 1999-2005 ComPiere, Inc.  All Rights Reserved.
 * Contributor(s): ______________________________________.
 *****************************************************************************/
package com.ampiere.search;

import java.math.BigDecimal;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Hashtable;
import java.util.Properties;
import java.util.logging.Level;

import org.apache.ecs.AlignType;
import org.compiere.util.Ctx;
import org.compiere.util.DB;
import org.compiere.util.Env;
import org.compiere.util.Msg;
import org.compiere.util.Util;

/**
 *  Info Payment
 *
 *  @author Jorg Janke
 *  @version  $Id: InfoPayment.java,v 1.1 2010/01/13 11:52:01 clmg Exp $
 */
public class InfoPayment extends Info
{
	/**  Array of Column Info    */
	private Info_Column[] s_paymentLayout = null;

	/**
	 *  Detail Protected Contructor
	 *  @param frame parent frame
	 *  @param modal modal
	 *  @param WindowNo window no
	 *  @param value query value
	 *  @param multiSelection multiple selections
	 *  @param whereClause whwre clause
	 */
	protected InfoPayment(int WindowNo, String value, boolean multiSelection, String whereClause, Ctx ctx)
	{
		super(WindowNo, "p", "C_Payment_ID", multiSelection, whereClause, ctx);

		log.info( "InfoPayment");
		title = Msg.translate(ctx, "InfoPayment");

		/**  Array of Column Info    */
		int i = 0;
		s_paymentLayout = new Info_Column [12];
		columnAttrList = new ArrayList<Integer>();
		s_paymentLayout[i++] = new Info_Column(Msg.translate(ctx, "Select"), "p.C_Payment_ID", IDColumn.class);
		columnAttrList.add(1);
		s_paymentLayout[i++] = new Info_Column(Msg.translate(ctx, "C_BankAccount_ID"), "(SELECT b.Name || ' ' || ba.AccountNo FROM C_Bank b, C_BankAccount ba WHERE b.C_Bank_ID=ba.C_Bank_ID AND ba.C_BankAccount_ID=p.C_BankAccount_ID)", String.class);
		columnAttrList.add(1);
		s_paymentLayout[i++] = new Info_Column(Msg.translate(ctx, "C_BPartner_ID"), "(SELECT Name FROM C_BPartner bp WHERE bp.C_BPartner_ID=p.C_BPartner_ID)", String.class);
		columnAttrList.add(1);
		s_paymentLayout[i++] = new Info_Column(Msg.translate(ctx, "DateTrx"), "p.DateTrx", Timestamp.class);
		columnAttrList.add(1);
		s_paymentLayout[i++] = new Info_Column(Msg.translate(ctx, "DocumentNo"), "p.DocumentNo", String.class);
		columnAttrList.add(1);
		s_paymentLayout[i++] = new Info_Column(Msg.translate(ctx, "IsReceipt"), "p.IsReceipt", Boolean.class);
		columnAttrList.add(0);
		s_paymentLayout[i++] = new Info_Column(Msg.translate(ctx, "C_Currency_ID"), "(SELECT ISO_Code FROM C_Currency c WHERE c.C_Currency_ID=p.C_Currency_ID)", String.class);
		columnAttrList.add(0);
		s_paymentLayout[i++] = new Info_Column(Msg.translate(ctx, "PayAmt"), "p.PayAmt",  BigDecimal.class);
		columnAttrList.add(0);
		s_paymentLayout[i++] = new Info_Column(Msg.translate(ctx, "ConvertedAmount"), "currencyBase(p.PayAmt,p.C_Currency_ID,p.DateTrx, p.AD_Client_ID,p.AD_Org_ID)", BigDecimal.class);
		columnAttrList.add(0);
		s_paymentLayout[i++] = new Info_Column(Msg.translate(ctx, "DiscountAmt"), "p.DiscountAmt",  BigDecimal.class);
		columnAttrList.add(0);
		s_paymentLayout[i++] = new Info_Column(Msg.translate(ctx, "WriteOffAmt"), "p.WriteOffAmt",  BigDecimal.class);
		columnAttrList.add(0);
		s_paymentLayout[i++] = new Info_Column(Msg.translate(ctx, "IsAllocated"), "p.IsAllocated",  Boolean.class);
		columnAttrList.add(0);

		//
		try
		{
			String s = "";
			if (value != null && value.length() > 0) {
				s = value;
			}
			statInit(ctx, s);
			p_loadedOK = initInfo();
		}
		catch (Exception e)
		{
			return;
		}
	}   //  InfoPayment

	/**
	 *	Static Setup - add fields to parameterPanel
	 *  @throws Exception if Lookups cannot be created
	 */
	private void statInit(Ctx ctx, String value) throws Exception
	{
		// First Row
		componentList.add(new ComponentBean(Msg.translate(ctx, "DocumentNo"), ComponentBean.TYPE_LABEL, "", AlignType.RIGHT, AlignType.MIDDLE, "", 0));
		componentMapping.put("DocumentNo", new Integer(componentList.size()));
		componentList.add(new ComponentBean("", ComponentBean.TYPE_TEXT, value, AlignType.LEFT, AlignType.MIDDLE, "", 220));

//		fBPartner_ID = new VLookup("C_BPartner_ID", false, false, true, MLookupFactory.get (ctx, p_WindowNo, 0, 3499, DisplayType.Search));
		componentList.add(new ComponentBean(Msg.translate(ctx, "BPartner"), ComponentBean.TYPE_LABEL, "", AlignType.RIGHT, AlignType.MIDDLE, "", 0));
		componentMapping.put("C_BPartner_ID", new Integer(componentList.size()));
		componentList.add(new ComponentBean("C_BPartner_ID", ComponentBean.TYPE_LOOKUP, "", AlignType.LEFT, AlignType.MIDDLE, "", 198));

//		String isSOTrx = ("N".equals(Env.getContext(ctx, p_WindowNo, "IsSOTrx")) ? "N" : "Y");
		String isSOTrx = ("N".equals(ctx.getContext(p_WindowNo, "IsSOTrx")) ? "N" : "Y");
		componentMapping.put("IsReceipt", new Integer(componentList.size()));
		ComponentBean bean = new ComponentBean(Msg.translate(ctx, "IsReceipt"), ComponentBean.TYPE_CHECKBOX, isSOTrx, AlignType.LEFT, AlignType.MIDDLE, "", 0);
		bean.setColSpan(2);
		componentList.add(bean);

		componentList.add(new ComponentBean(ComponentBean.TYPE_BR));

		// 2nd Row
		componentList.add(new ComponentBean(ComponentBean.TYPE_LABEL));
		componentList.add(new ComponentBean(ComponentBean.TYPE_LABEL));
		componentList.add(new ComponentBean(Msg.translate(ctx, "DateTrx"), ComponentBean.TYPE_LABEL, "", AlignType.RIGHT, AlignType.MIDDLE, "", 0));
		componentMapping.put("DateFrom", new Integer(componentList.size()));
		componentList.add(new ComponentBean(Msg.translate(ctx, "DateFrom"), ComponentBean.TYPE_DATE, "", AlignType.LEFT, AlignType.MIDDLE, "", 198));
		componentList.add(new ComponentBean("-", ComponentBean.TYPE_LABEL, "", AlignType.CENTER, AlignType.MIDDLE, "", 0));
		componentMapping.put("DateTo", new Integer(componentList.size()));
		componentList.add(new ComponentBean(Msg.translate(ctx, "DateTo"), ComponentBean.TYPE_DATE, "", AlignType.LEFT, AlignType.MIDDLE, "", 198));

		componentList.add(new ComponentBean(ComponentBean.TYPE_BR));

		// 3rd Row
		componentList.add(new ComponentBean(ComponentBean.TYPE_LABEL));
		componentList.add(new ComponentBean(ComponentBean.TYPE_LABEL));
		componentList.add(new ComponentBean(Msg.translate(ctx, "PayAmt"), ComponentBean.TYPE_LABEL, "", AlignType.RIGHT, AlignType.MIDDLE, "", 0));
		componentMapping.put("AmtFrom", new Integer(componentList.size()));
		componentList.add(new ComponentBean(Msg.translate(ctx, "AmtFrom"), ComponentBean.TYPE_TEXT, "", AlignType.LEFT, AlignType.MIDDLE, "", 220));
		componentList.add(new ComponentBean("-", ComponentBean.TYPE_LABEL, "", AlignType.CENTER, AlignType.MIDDLE, "", 0));
		componentMapping.put("AmtTo", new Integer(componentList.size()));
		componentList.add(new ComponentBean(Msg.translate(ctx, "AmtTo"), ComponentBean.TYPE_TEXT, "", AlignType.LEFT, AlignType.MIDDLE, "", 220));
	}	// statInit

	/**
	 *	General Init
	 *	@return true, if success
	 */
	private boolean initInfo ()
	{
		//  prepare table
		StringBuffer where = new StringBuffer("p.IsActive='Y'");
		if (p_whereClause.length() > 0)
			where.append(" AND ").append(Util.replace(p_whereClause, "C_Payment.", "p."));
		prepareTable(s_paymentLayout,
			" C_Payment_v p",
			where.toString(),
			"2,3,4");

		return true;
	}	//	initInfo

	/**
	 *	Construct SQL Where Clause and define parameters.
	 *  (setParameters needs to set parameters)
	 *  Includes first AND
	 *  @return sql
	 */
	protected String createQuery(Hashtable valueMapping, SimpleDateFormat dateFormat) {
		StringBuffer sql = new StringBuffer();

		// DocumentNo
		String s = getComponetValue(valueMapping, "DocumentNo");
		if (s != null)
		{
			s = s.toUpperCase();
			if (! s.endsWith("%"))
				s += "%";
			sql.append(" AND UPPER(p.DocumentNo) LIKE ");
			sql.append(DB.TO_STRING(s));
		}

		// Business Partner
		s = getComponetValue(valueMapping, "C_BPartner_ID");
		if (s != null)
		{
			sql.append(" AND p.C_BPartner_ID=");
			sql.append(Integer.parseInt(s));
		}

		// Transaction date
		String from = getComponetValue(valueMapping, "DateFrom");
		String to = getComponetValue(valueMapping, "DateTo");
		if (from != null || to != null)
		{
			Timestamp fromT = null;
			Timestamp toT = null;
			try {
				if (from != null) {
					Date d = dateFormat.parse(from);
					fromT = new Timestamp(d.getTime());
				}
				if (to != null) {
					Date d = dateFormat.parse(to);
					toT = new Timestamp(d.getTime());
				}
			} catch (Exception e) {
				log.log(Level.SEVERE, "InfoInOut : createQuery : Date convert error ", e);
			}

			if (fromT == null && toT != null) {
				sql.append(" AND TRUNC(p.DateTrx) <= ");
				sql.append(DB.TO_DATE(toT, true));
			} else if (fromT != null && toT == null) {
				sql.append(" AND TRUNC(p.DateTrx) >= ");
				sql.append(DB.TO_DATE(fromT, true));
			} else if (from != null && to != null) {
				sql.append(" AND TRUNC(p.DateTrx) BETWEEN ");
				sql.append(DB.TO_DATE(fromT, true));
				sql.append(" AND ");
				sql.append(DB.TO_DATE(toT, true));
			}
		}

		// Pay Amount
		from = getComponetValue(valueMapping, "AmtFrom");
		to = getComponetValue(valueMapping, "AmtTo");
		if (from != null || to != null)
		{
			BigDecimal fromB = null;
			BigDecimal toB = null;
			try {
				fromB = new BigDecimal(from);
				toB = new BigDecimal(to);
			} catch (Exception e) {
				log.log(Level.SEVERE, "InfoPayment : createQuery : To BigDecimal ", e);
			}
			if (fromB == null && toB != null) {
				sql.append(" AND p.PayAmt <= ");
				sql.append(toB);
			} else if (from != null && to == null) {
				sql.append(" AND p.PayAmt >= ");
				sql.append(fromB);
			} else if (from != null && to != null) {
				sql.append(" AND p.PayAmt BETWEEN ");
				sql.append(fromB);
				sql.append(" AND ");
				sql.append(toB);
			}
		}

		// Is receipt
		s = getComponetValue(valueMapping, "IsReceipt");
		if (s != null)
		{
			s = s.toUpperCase();
			sql.append(" AND p.IsReceipt=");
			sql.append("'" + s + "'");
		}

		log.fine(sql.toString());
		return sql.toString();
	}	//	getSQLWhere

	/**
	 *  Set Parameters for Query.
	 *  (as defined in getSQLWhere)
	 *  @param pstmt statement
	 *  @param forCount for counting records
	 *  @throws SQLException
	 */
	void setParameters(PreparedStatement pstmt, boolean forCount) throws SQLException
	{
	}   //  setParameters

	/**************************************************************************
	 *  Get dynamic WHERE part of SQL
	 *	To be overwritten by concrete classes
	 *  @return WHERE clause
	 */
	protected String getSQLWhere() {
		if (p_sqlWhere != null && p_sqlWhere.length() > 0) {
			return p_sqlWhere;
		}
		return "";
	}
}   //  InfoPayment
