/******************************************************************************
 * 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 org.compiere.apps.search;

import java.awt.Frame;
import java.awt.event.ActionListener;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;

import org.compiere.apps.AEnv;
import org.compiere.apps.ALayout;
import org.compiere.apps.ALayoutConstraint;
import org.compiere.framework.Info_Column;
import org.compiere.minigrid.IDColumn;
import org.compiere.plaf.CompierePLAF;
import org.compiere.swing.CLabel;
import org.compiere.swing.CTextField;
import org.compiere.util.Env;
import org.compiere.util.KeyNamePair;
import org.compiere.util.Msg;

/**
 *	Search Postal and return selection
 *
 * 	@author 	Jorg Janke
 * 	@version 	$Id: InfoPostal.java,v 1.1 2008/02/14 13:02:23 jrmt Exp $
 */
public class InfoPostal extends Info implements ActionListener
{
	/**
	 *	Standard Constructor
	 *  @param frame frame
	 *  @param modal modal
	 *  @param WindowNo WindowNo
	 *  @param  value   Query value Name or Value if contains numbers
	 *  @param isSOTrx  if false, query vendors only
	 *  @param multiSelection multiple selection
	 *  @param whereClause where clause
	 */
	public InfoPostal(Frame frame, boolean modal, int windowNo, int C_Country_ID,
		String value, boolean multiSelection, String whereClause)
	{
		super (frame, modal, windowNo, "X_Postal", "Postal_ID", multiSelection, whereClause);
		log.info(value);
		setTitle(Msg.getMsg(Env.getCtx(), "InfoPostal"));

		m_C_Country_ID = C_Country_ID;
		//
		statInit();
		initInfo (value, whereClause);
		//
		int no = p_table.getRowCount();
		setStatusLine(Integer.toString(no) + " " + Msg.getMsg(Env.getCtx(), "SearchRows_EnterQuery"), false);
		setStatusDB(Integer.toString(no));
		//	AutoQuery
		if (value != null && value.length() > 0)
			executeQuery();
		p_loadedOK = true;
		//	Focus
		fieldValue.requestFocus();

		AEnv.positionCenterWindow(frame, this);
	}	//	InfoPostal

	private int m_X_Postal_ID = -1;
	
	private int m_C_Country_ID = -1;

	/** From Clause             */
	private static String s_postalFROM = "X_Postal"
		+ " LEFT OUTER JOIN C_Country c ON (X_Postal.C_Country_ID=c.C_Country_ID AND c.IsActive='Y')"
		+ " LEFT OUTER JOIN C_Region r ON (X_Postal.C_Region_ID=r.C_Region_ID AND r.IsActive='Y')";

	/**  Array of Column Info    */
	private static Info_Column[] s_postalLayout = {
		new Info_Column(" ", "X_Postal.X_Postal_ID", IDColumn.class),
		new Info_Column(Msg.translate(Env.getCtx(), "Postal"), "X_Postal.Postal", String.class),
		new Info_Column(Msg.translate(Env.getCtx(), "Country"), "c.Name AS Country", KeyNamePair.class, "c.C_Country_ID"),
		new Info_Column(Msg.translate(Env.getCtx(), "Region"), "r.Name AS Region", KeyNamePair.class, "r.C_Region_ID"),
		new Info_Column(Msg.translate(Env.getCtx(), "X_City_Name"), "X_Postal.X_City_Name", String.class),
		new Info_Column(Msg.translate(Env.getCtx(), "X_Address"), "X_Postal.X_Address", String.class),
		new Info_Column(Msg.translate(Env.getCtx(), "X_Region_Name_Kana"), "X_Postal.X_Region_Name_Kana", String.class),
		new Info_Column(Msg.translate(Env.getCtx(), "X_City_Name_Kana"), "X_Postal.X_City_Name_Kana", String.class),
		new Info_Column(Msg.translate(Env.getCtx(), "X_Address_Kana"), "X_Postal.X_Address_Kana", String.class),
	};

	/**
	 *	Get Layout
	 *	@return array of Column_Info
	 */
	protected Info_Column[] getInfoColumns()
	{
		return s_postalLayout;
	}	//	getInfoColumns

	//
	private CLabel labelValue = new CLabel();
	private CTextField fieldValue = new CTextField(10);
	private CLabel labelRegion = new CLabel();
	private CTextField fieldRegion = new CTextField(10);
	private CLabel labelCity = new CLabel();
	private CTextField fieldCity = new CTextField(10);
	private CLabel labelAddress = new CLabel();
	private CTextField fieldAddress = new CTextField(10);

	/**
	 *	Static Setup - add fields to parameterPanel
	 */
	private void statInit()
	{
		labelValue.setText(Msg.getMsg(Env.getCtx(), "Postal"));
		fieldValue.setBackground(CompierePLAF.getInfoBackground());
		fieldValue.addActionListener(this);

		labelRegion.setText(Msg.getMsg(Env.getCtx(), "Region"));
		fieldRegion.setBackground(CompierePLAF.getInfoBackground());
		fieldRegion.addActionListener(this);

		labelCity.setText(Msg.getMsg(Env.getCtx(), "City"));
		fieldCity.setBackground(CompierePLAF.getInfoBackground());
		fieldCity.addActionListener(this);
		
		labelAddress.setText(Msg.getMsg(Env.getCtx(), "Address"));
		fieldAddress.setBackground(CompierePLAF.getInfoBackground());
		fieldAddress.addActionListener(this);

		//
		parameterPanel.setLayout(new ALayout());
		//
		parameterPanel.add(labelValue, new ALayoutConstraint(0,0));
		parameterPanel.add(fieldValue, null);
		parameterPanel.add(labelRegion, null);
		parameterPanel.add(fieldRegion, null);
		parameterPanel.add(labelCity, null);
		parameterPanel.add(fieldCity, null);
		parameterPanel.add(labelAddress, null);
		parameterPanel.add(fieldAddress, null);
		
	}	//	statInit

	/**
	 *	Dynamic Init
	 *  @param value value
	 *  @param whereClause where clause
	 */
	private void initInfo(String value, String whereClause)
	{

		//	Create Grid
		StringBuffer where = new StringBuffer();
		where.append("X_Postal.IsActive='Y' AND C_Country_ID="+m_C_Country_ID);
		if (whereClause != null && whereClause.length() > 0)
			where.append(" AND ").append(whereClause);
		//
		prepareTable(s_postalFROM,
			where.toString(),
			"X_Postal.Postal");

		//  Set Value
		if (value == null)
			value = "%";
		if (!value.endsWith("%"))
			value += "%";

		//	Put query string in Name if not numeric
		if (value.equals("%"))
			fieldValue.setText(value);
		//	No Numbers entered
		else if ((value.indexOf("0")+value.indexOf("1")+value.indexOf("2")+value.indexOf("3")+value.indexOf("4") +value.indexOf("5")
			+value.indexOf("6")+value.indexOf("7")+value.indexOf("8")+value.indexOf("9")) == -10)
		{
			if (value.startsWith("%"))
				fieldValue.setText(value);
			else
				fieldValue.setText("%" + value);
		}
		//	Number entered
		else
			fieldValue.setText(value);
	}	//	initInfo

	/*************************************************************************/

	/**
	 *	Construct SQL Where Clause and define parameters.
	 *  (setParameters needs to set parameters)
	 *  Includes first AND
	 *  @return WHERE clause
	 */
	public String getSQLWhere()
	{
		ArrayList<String> list = new ArrayList<String>();
		//	=> Value
		String value = fieldValue.getText();
		if (!(value.equals("") || value.equals("%")))
			list.add ("X_Postal.Postal LIKE ?");
		
		//	=> Region
		String region = fieldRegion.getText();
		if (!(region.equals("") || region.equals("%")))
			list.add ("X_Postal.X_Region_Name LIKE ?");
		
		//	=> City
		String city = fieldCity.getText();
		if (!(city.equals("") || city.equals("%")))
			list.add ("X_Postal.X_City_Name LIKE ?");
		
		//	=> Address
		String address = fieldAddress.getText();
		if (!(address.equals("") || address.equals("%")))
			list.add ("X_Postal.X_Address LIKE ?");
		
		StringBuffer sql = new StringBuffer();
		int size = list.size();
		//	Just one
		if (size == 1)
			sql.append(" AND ").append(list.get(0));
		else if (size > 1)
		{
			sql.append(" AND ");
			for (int i = 0; i < size; i++)
			{
				if (i > 0)
					sql.append(" AND ");
				sql.append(list.get(i));
			}
		}

		return sql.toString();
	}	//	getSQLWhere

	/**
	 *  Set Parameters for Query.
	 *  (as defined in getSQLWhere)
	 *  @param pstmt pstmt
	 *  @param forCount for counting records
	 *  @throws SQLException
	 */
	void setParameters(PreparedStatement pstmt, boolean forCount) throws SQLException
	{
		int index = 1;
		//	=> Value
		String value = fieldValue.getText();
		if (!(value.equals("") || value.equals("%")))
		{
			if (!value.endsWith("%"))
				value += "%";
			pstmt.setString(index++, value);
			log.fine("Value: " + value);
		}
		
		//	=> Region
		String region = fieldRegion.getText();
		if (!(region.equals("") || region.equals("%")))
		{
			if (!region.endsWith("%"))
				region += "%";
			pstmt.setString(index++, region);
			log.fine("Region: " + region);
		}
		//	=> City
		String city = fieldCity.getText();
		if (!(city.equals("") || city.equals("%")))
		{
			if (!city.endsWith("%"))
				city += "%";
			pstmt.setString(index++, city);
			log.fine("City: " + city);
		}
		//	=> Address
		String address = fieldAddress.getText();
		if (!(address.equals("") || address.equals("%")))
		{
			if (!address.endsWith("%"))
				address += "%";
			pstmt.setString(index++, address);
			log.fine("Address: " + address);
		}
		
	}   //  setParameters

	/*************************************************************************/

	/**
	 *  Save Selection Details
	 *  Get Location/Partner Info
	 */
	public void saveSelectionDetail()
	{
		int row = p_table.getSelectedRow();
		if (row == -1)
			return;

		//  publish for Callout to read
		Integer ID = getSelectedRowKey();
		
		m_X_Postal_ID = ID.intValue();
		
	}   //  saveSelectionDetail


	/**************************************************************************
	 *	Show History
	 */
	void showHistory()
	{
		log.info("");
		Integer C_BPartner_ID = getSelectedRowKey();
		if (C_BPartner_ID == null)
			return;
		InvoiceHistory ih = new InvoiceHistory (this, C_BPartner_ID.intValue(), 
			0, 0, 0);
		ih.setVisible(true);
		ih = null;
	}	//	showHistory

	/**
	 *	Has History
	 *  @return true
	 */
	boolean hasHistory()
	{
		return true;
	}	//	hasHistory

	/**
	 *	Has Zoom
	 *  @return true
	 */
	boolean hasZoom()
	{
		return false;
	}	//	hasZoom

	/**
	 *	Customize
	 */
	void customize()
	{
		log.info( "InfoPostal.customize");
	}	//	customize

	/**
	 *	Has Customize
	 *  @return false
	 */
	boolean hasCustomize()
	{
		return false;	//	for now
	}	//	hasCustomize

}	//	InfoBPartner
