/******************************************************************************
 * Product: Compiere ERP & CRM Smart Business Solution                        *
 * Copyright (C) 1999-2007 ComPiere, Inc. All Rights Reserved.                *
 * This program is free software, you can redistribute it and/or modify it    *
 * under the terms version 2 of the GNU General Public License as published   *
 * by the Free Software Foundation. This program is distributed in the hope   *
 * that it will be useful, but WITHOUT ANY WARRANTY, without even the implied *
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.           *
 * See the GNU General Public License for more details.                       *
 * You should have received a copy of the GNU General Public License along    *
 * with this program, if not, write to the Free Software Foundation, Inc.,    *
 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.                     *
 * For the text or an alternative of this public license, you may reach us    *
 * ComPiere, Inc., 3600 Bridge Parkway #102, Redwood City, CA 94065, USA      *
 * or via info@compiere.org or http://www.compiere.org/license.html           *
 *****************************************************************************/
package org.compiere.grid.ed;

import java.awt.BorderLayout;
import java.awt.Frame;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.StringTokenizer;
import java.util.logging.Level;

import javax.swing.Box;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.SwingConstants;

import org.compiere.apps.AEnv;
import org.compiere.apps.AppsAction;
import org.compiere.apps.ConfirmPanel;
import org.compiere.apps.search.InfoPostal;
import org.compiere.model.MCountry;
import org.compiere.model.MLocation;
import org.compiere.model.MRegion;
import org.compiere.swing.CButton;
import org.compiere.swing.CComboBox;
import org.compiere.swing.CDialog;
import org.compiere.swing.CLabel;
import org.compiere.swing.CPanel;
import org.compiere.swing.CTextField;
import org.compiere.util.CLogger;
import org.compiere.util.DB;
import org.compiere.util.Env;
import org.compiere.util.Msg;

/**
 *	Dialog to enter Location Info (Address)
 *
 *  @author 	Jorg Janke
 *  @version 	$Id: VLocationDialog.java,v 1.2 2008/02/14 13:02:23 jrmt Exp $
 */
public class VLocationDialog extends CDialog implements ActionListener
{
	/**
	 *	Constructor
	 *
	 * @param frame parent
	 * @param title title (field name)
	 * @param location Model Location
	 */
	public VLocationDialog (Frame frame, String title, MLocation location)
	{
		super(frame, title, true);
		try
		{
			jbInit();
		}
		catch(Exception ex)
		{
			log.log(Level.SEVERE, ex.getMessage());
		}
		m_location = location;
		if (m_location == null) {
			m_location = m_tempLocation;
		}
		
		//	Overwrite title	
		if (m_location.getC_Location_ID() == 0)
			setTitle(Msg.getMsg(Env.getCtx(), "LocationNew"));
		else
			setTitle(Msg.getMsg(Env.getCtx(), "LocationUpdate"));
		

		//	Current Country
		MCountry.setDisplayLanguage(Env.getAD_Language(Env.getCtx()));
		fCountry = new CComboBox(MCountry.getCountries(Env.getCtx()));
		fCountry.setSelectedItem(m_location.getCountry());
		m_origCountry_ID = m_location.getC_Country_ID();
		//	Current Region
		fRegion = new CComboBox(MRegion.getRegions(Env.getCtx(), m_origCountry_ID));
		if (m_location.getCountry().isHasRegion())
			lRegion.setText(m_location.getCountry().getRegionName());	//	name for region
		fRegion.setSelectedItem(m_location.getRegion());
		//
		initLocation();
		fCountry.addActionListener(this);
		AEnv.positionCenterWindow(frame, this);
	}	//	VLocationDialog

	// Jirimuto Added for Postal Lookup 2008/01/18
	private Frame	m_frame;
	private int		m_windowNo = 0;
	
	private boolean 	m_change = false;
	private MLocation	m_location;
	private MLocation	m_tempLocation = new MLocation (Env.getCtx(), 0, null);
	private int			m_origCountry_ID;
	private int			s_oldCountry_ID = 0;
	/**	Logger			*/
	private static CLogger log = CLogger.getCLogger(VLocationDialog.class);

	private CPanel panel = new CPanel();
	private CPanel mainPanel = new CPanel();
	private CPanel southPanel = new CPanel();
	private BorderLayout panelLayout = new BorderLayout();
	private GridBagLayout gridBagLayout = new GridBagLayout();
	private ConfirmPanel confirmPanel = new ConfirmPanel(true);
	private BorderLayout southLayout = new BorderLayout();
	//
	private CLabel		lAddress1   = new CLabel(Msg.getMsg(Env.getCtx(), "Address")+ " 1");
	private CLabel		lAddress2   = new CLabel(Msg.getMsg(Env.getCtx(), "Address")+ " 2");
	private CLabel		lAddress3   = new CLabel(Msg.getMsg(Env.getCtx(), "Address")+ " 3");
	private CLabel		lAddress4   = new CLabel(Msg.getMsg(Env.getCtx(), "Address")+ " 4");
	private CLabel		lCity       = new CLabel(Msg.getMsg(Env.getCtx(), "City"));
	private CLabel		lCountry    = new CLabel(Msg.getMsg(Env.getCtx(), "Country"));
	private CLabel		lRegion     = new CLabel(Msg.getMsg(Env.getCtx(), "Region"));
	private CLabel		lPostal     = new CLabel(Msg.getMsg(Env.getCtx(), "Postal"));
	private CLabel		lPostalAdd  = new CLabel(Msg.getMsg(Env.getCtx(), "PostalAdd"));
	private CTextField	fAddress1 = new CTextField(20);		//	length=60
	private CTextField	fAddress2 = new CTextField(20);		//	length=60
	private CTextField	fAddress3 = new CTextField(20);		//	length=60
	private CTextField	fAddress4 = new CTextField(20);		//	length=60
	private CTextField	fCity  = new CTextField(15);		//	length=60
	private CComboBox	fCountry;
	private CComboBox	fRegion;
	private CTextField	fPostal = new CTextField(5);		//	length=10
	private CTextField	fPostalAdd = new CTextField(5);		//	length=10

	/**
	 *  Jirimuto added for Postal Lookup 2008/01/18
	 */
	private CLabel		lPostalLookup = new CLabel("");
	private CButton     fPostalLookup = new CButton(Msg.getMsg(Env.getCtx(), "PostalLookup"));

	/** The "to link" key  */
	private static final String TO_LINK = "ToLink";

	/** The "to link" Button  */
	private AppsAction 	m_toMapAction =
		new AppsAction(TO_LINK, null, Msg.getMsg(Env.getCtx(), TO_LINK));
	
	//
	private GridBagConstraints gbc = new GridBagConstraints();
	private Insets labelInsets = new Insets(2,15,2,0);		// 	top,left,bottom,right
	private Insets fieldInsets = new Insets(2,5,2,10);

	/**
	 *	Static component init
	 *  @throws Exception
	 */
	void jbInit() throws Exception
	{
		panel.setLayout(panelLayout);
		southPanel.setLayout(southLayout);
		mainPanel.setLayout(gridBagLayout);
		panelLayout.setHgap(5);
		panelLayout.setVgap(10);
		getContentPane().add(panel);
		panel.add(mainPanel, BorderLayout.CENTER);
		panel.add(southPanel, BorderLayout.SOUTH);
		southPanel.add(confirmPanel, BorderLayout.CENTER);

		m_toMapAction.getButton().setMargin(ConfirmPanel.s_insets);
		m_toMapAction.setDelegate(this);
		confirmPanel.addComponent(m_toMapAction.getButton());
		//
		confirmPanel.addActionListener(this);
	}	//	jbInit

	
	
	private void renderCountrySpecificFields()
	{
		mainPanel.remove(lCity);
		mainPanel.remove(fCity);
		mainPanel.remove(lPostal);
		mainPanel.remove(fPostal);
		mainPanel.remove(lPostalAdd);
		mainPanel.remove(fPostalAdd);
		mainPanel.remove(lRegion);
		mainPanel.remove(fRegion);
		
		
		MCountry country = m_location.getCountry();

		//  sequence of City Postal Region - @P@ @C@ - @C@, @R@ @P@
		String ds = country.getDisplaySequence();
		if (ds == null || ds.length() == 0)
		{
			log.log(Level.SEVERE, "DisplaySequence empty - " + country);
			ds = "";	//	@C@,  @P@
		}
		int line = 5;
		StringTokenizer st = new StringTokenizer(ds, "@", false);
		while (st.hasMoreTokens())
		{
			String s = st.nextToken();
			if (s.startsWith("C"))
				addLine(line++, lCity, fCity);
			else if (s.startsWith("P"))
				addLine(line++, lPostal, fPostal);
			else if (s.startsWith("A"))
				addLine(line++, lPostalAdd, fPostalAdd);
			else if (s.startsWith("R") && m_location.getCountry().isHasRegion())
				addLine(line++, lRegion, fRegion);
		}
		
	}
	
	/**
	 *	Dynanmic Init & fill fields - Called when Country changes!
	 */
	private void initLocation()
	{
		MCountry country = m_location.getCountry();
		log.fine(country.getName() + ", Region=" + country.isHasRegion() + " " + country.getDisplaySequence()
			+ ", C_Location_ID=" + m_location.getC_Location_ID());
		//	new Region
		if (m_location.getC_Country_ID() != s_oldCountry_ID && country.isHasRegion())
		{
			fRegion = new CComboBox(MRegion.getRegions(Env.getCtx(), country.getC_Country_ID()));
			if (m_location.getRegion() != null)
				fRegion.setSelectedItem(m_location.getRegion());
			lRegion.setText(country.getRegionName());
			s_oldCountry_ID = m_location.getC_Country_ID();
		}

		gbc.anchor = GridBagConstraints.NORTHWEST;
		gbc.gridy = 0;			//	line
		gbc.gridx = 0;
		gbc.gridwidth = 1;
		gbc.insets = fieldInsets;
		gbc.fill = GridBagConstraints.HORIZONTAL;
		gbc.weightx = 0;
		gbc.weighty = 0;

		mainPanel.add(Box.createVerticalStrut(5), gbc);    	//	top gap

		/**
		 *  Jirimuto Modified 2008/01/18
		 */
		boolean AddressLinesLocalReverseFlg = country.isAddressLinesLocalReverse();
		int line = 1;
		
		if( AddressLinesLocalReverseFlg ){
			//  Country Last
			addLine(line++, lCountry, fCountry);
			
			//  sequence of City Postal Region - @P@ @C@ - @C@, @R@ @P@
			String ds = country.getDisplaySequenceLocal();
			if (ds == null || ds.length() == 0)
			{
				log.log(Level.SEVERE, "DisplaySequence empty - " + country);
				ds = "";	//	@C@,  @P@
			}
			StringTokenizer st = new StringTokenizer(ds, "@", false);
			while (st.hasMoreTokens())
			{
				String s = st.nextToken();
				if (s.startsWith("C"))
					addLine(line++, lCity, fCity);
				else if (s.startsWith("P"))
					addLine(line++, lPostal, fPostal);
				else if (s.startsWith("A")){
					addLine(line++, lPostalAdd, fPostalAdd);
					addLine(line++, lPostalLookup, fPostalLookup);
					fPostalLookup.addActionListener(this);
				}
				else if (s.startsWith("R") && m_location.getCountry().isHasRegion())
					addLine(line++, lRegion, fRegion);
			}
			
			addLine(line++, lAddress1, fAddress1);
			addLine(line++, lAddress2, fAddress2);
			addLine(line++, lAddress3, fAddress3);
			addLine(line++, lAddress4, fAddress4);

		} else {

			addLine(line++, lAddress1, fAddress1);
			addLine(line++, lAddress2, fAddress2);
			addLine(line++, lAddress3, fAddress3);
			addLine(line++, lAddress4, fAddress4);

			renderCountrySpecificFields();
			
			line += 9;
			//  Country Last
			addLine(line++, lCountry, fCountry);
			
		}
		//	Fill it
		if (m_location.getC_Location_ID() != 0)
		{
			fAddress1.setText(m_location.getAddress1());
			fAddress2.setText(m_location.getAddress2());
			fAddress3.setText(m_location.getAddress3());
			fAddress4.setText(m_location.getAddress4());
			fCity.setText(m_location.getCity());
			fPostal.setText(m_location.getPostal());
			fPostalAdd.setText(m_location.getPostal_Add());
			if (m_location.getCountry().isHasRegion())
			{
				lRegion.setText(m_location.getCountry().getRegionName());
				fRegion.setSelectedItem(m_location.getRegion());
			}
			fCountry.setSelectedItem(country);
		}
		//	Update UI
		pack();
	}	//	initLocation

	/**
	 *	Add Line to screen
	 *
	 *  @param line line number (zero based)
	 *  @param label label
	 *  @param field field
	 */
	private void addLine(int line, JLabel label, JComponent field)
	{
		gbc.gridy = line;
		//	label
		gbc.insets = labelInsets;
		gbc.gridx = 0;
		gbc.weightx = 0.0;
		gbc.fill = GridBagConstraints.HORIZONTAL;
		label.setHorizontalAlignment(SwingConstants.RIGHT);
		mainPanel.add(label, gbc);
		//	Field
		gbc.insets = fieldInsets;
		gbc.gridx = 1;
		gbc.weightx = 1.0;
		gbc.fill = GridBagConstraints.NONE;
		mainPanel.add(field, gbc);
	}	//	addLine


	/**
	 *	ActionListener
	 *  @param e ActionEvent
	 */
	public void actionPerformed(ActionEvent e)
	{
		if (e.getActionCommand().equals(ConfirmPanel.A_OK))
		{
			action_OK();
			m_change = true;
			dispose();
		}
		else if (e.getActionCommand().equals(ConfirmPanel.A_CANCEL))
		{
			m_change = false;
			dispose();
		}
		/**
		 *  Jirimuto Modified 2008/01/18
		 */
		//	Clicked The Postal Lookup Button
		else if (e.getSource() == fPostalLookup)
		{
			action_PostalLookup();
		}
		else if (e.getSource() == fCountry)
		{
			//	Country Changed - display in new Format
			//	Modifier for Mouse selection is 16  - for any key selection 0
			MCountry c = (MCountry)fCountry.getSelectedItem();
			m_location.setCountry(c);
			//	refrseh
			/**
			 *  Jirimuto Modified 2008/01/18
			 */
			mainPanel.removeAll();
			initLocation();
			
			fCountry.requestFocus();	//	allows to use Keybord selection
			
		}
		else
		{			
			//  Country/Region
			Env.startBrowser(Env.GOOGLE_MAPS_URL_PREFIX + getCurrentLocation());
		}
	}	//	actionPerformed

	/**
	 * 	OK - check for changes (save them) & Exit
	 */
	private void action_OK()
	{
		m_location.setAddress1(fAddress1.getText());
		m_location.setAddress2(fAddress2.getText());
		m_location.setAddress3(fAddress3.getText());
		m_location.setAddress4(fAddress4.getText());
		m_location.setCity(fCity.getText());
		m_location.setPostal(fPostal.getText());
		m_location.setPostal_Add(fPostalAdd.getText());
		//  Country/Region
		MCountry c = (MCountry)fCountry.getSelectedItem();
		m_location.setCountry(c);
		if (m_location.getCountry().isHasRegion())
		{
			MRegion r = (MRegion)fRegion.getSelectedItem();
			m_location.setRegion(r);
		}
		else
			m_location.setC_Region_ID(0);
		//	Save chnages
		m_location.save();
	}	//	actionOK

	/**
	 *	Get result
	 *  @return true, if changed
	 */
	public boolean isChanged()
	{
		return m_change;
	}	//	getChange

	/**
	 * 	Get edited Value (MLocation)
	 *	@return location
	 */
	public MLocation getValue()
	{
		return m_location;
	}	//	getValue

	/**
	 * 	Get edited Value (MLocation)
	 *	@return location
	 */
	private String getCurrentLocation() {
		m_tempLocation.setAddress1(fAddress1.getText());
		m_tempLocation.setAddress2(fAddress2.getText());
		m_tempLocation.setAddress3(fAddress3.getText());
		m_tempLocation.setAddress4(fAddress4.getText());
		m_tempLocation.setCity(fCity.getText());
		m_tempLocation.setPostal(fPostal.getText());
		m_tempLocation.setPostal_Add(fPostalAdd.getText());
		//  Country/Region
		MCountry c = (MCountry)fCountry.getSelectedItem();
		m_tempLocation.setCountry(c);
		if (m_tempLocation.getCountry().isHasRegion())
		{
			MRegion r = (MRegion)fRegion.getSelectedItem();
			m_tempLocation.setRegion(r);
		}
		else
			m_tempLocation.setC_Region_ID(0);
		
		return m_tempLocation.toString();
	}
	
	/**
	 *  Jirimuto Added for Postal lookup 2007/01/18
	 */
	private void action_PostalLookup()
	{
		/*********************************************************************/
		fPostal.setText(fPostal.getText().trim());
		fPostalAdd.setText(fPostalAdd.getText().trim());
		
		String value = fPostal.getText()+fPostalAdd.getText();

		int count = 0;
		PreparedStatement pstmt = null;
		StringBuffer sql = new StringBuffer ("SELECT COUNT(X_POSTAL_ID) " 
		    + " FROM X_POSTAL"
			+ " WHERE IsActive='Y'" +
			" AND C_COUNTRY_ID=" + m_location.getC_Country_ID());
		sql.append( " AND POSTAL like '" + value +"%'" );
		try
		{
			pstmt = DB.prepareStatement (sql.toString(), null);
			ResultSet rs = pstmt.executeQuery ();
			if ( rs.next () )
			{
				count = rs.getInt(1);
			}
			rs.close ();
			pstmt.close ();
			pstmt = null;
		}
		catch (Exception e)
		{
			log.log(Level.SEVERE, sql.toString(), e);
			try
			{
				if (pstmt != null)
					pstmt.close ();
			}
			catch (Exception pe)
			{
				;
			}
			pstmt = null;
		}
		
		if( count == 1 ){
			
			pstmt = null;
			sql = new StringBuffer ("SELECT C_REGION_ID, X_CITY_NAME, X_ADDRESS" 
			    + " FROM X_POSTAL"
				+ " WHERE IsActive='Y'" +
				" AND C_COUNTRY_ID=" + m_location.getC_Country_ID());
			sql.append( " AND POSTAL like '" + value +"%'" );
			try
			{
				pstmt = DB.prepareStatement (sql.toString(), null);
				ResultSet rs = pstmt.executeQuery ();
				if ( rs.next () )
				{
					int c_Region_ID = rs.getInt(1);
					String x_City_Name = rs.getString(2);
					String x_Address = rs.getString(3);
					MRegion region = MRegion.get(Env.getCtx(), c_Region_ID);
					fRegion.setSelectedItem( region ) ;
					fCity.setText( x_City_Name );
	
					String oldAddress = fAddress1.getText();
					if( oldAddress==null || !oldAddress.startsWith( x_Address )){
						fAddress1.setText( x_Address );
					}
				}
				rs.close ();
				pstmt.close ();
				pstmt = null;
			}
			catch (Exception e)
			{
				log.log(Level.SEVERE, sql.toString(), e);
				try
				{
					if (pstmt != null)
						pstmt.close ();
				}
				catch (Exception pe)
				{
				}
				pstmt = null;
			}
			
			
		} else {
			
			InfoPostal postal = new InfoPostal(m_frame, true, m_windowNo, m_location.getC_Country_ID(), 
					value, false, null );
			postal.setVisible(true);
			if( postal.isCancelled() ){
				return;
			}
			Integer id = (Integer)postal.getSelectedKey();
			
			pstmt = null;
			sql = new StringBuffer ("SELECT SUBSTR(POSTAL, 1, 3) AS POSTAL, SUBSTR(POSTAL, 4, 4) AS POSTALADD, " 
				+ " C_REGION_ID, X_CITY_NAME, X_ADDRESS" 
			    + " FROM X_POSTAL"
				+ " WHERE IsActive='Y'" +
				" AND C_COUNTRY_ID=" + m_location.getC_Country_ID());
			sql.append( " AND X_POSTAL_ID=" + id );
			try
			{
				pstmt = DB.prepareStatement (sql.toString(), null);
				ResultSet rs = pstmt.executeQuery ();
				if ( rs.next () )
				{
					String x_Postal = rs.getString(1);
					String x_PostalAdd = rs.getString(2);
					fPostal.setText(x_Postal);
					fPostalAdd.setText(x_PostalAdd);
					
					int c_Region_ID = rs.getInt(3);
					String x_City_Name = rs.getString(4);
					String x_Address = rs.getString(5);
					MRegion region = MRegion.get(Env.getCtx(), c_Region_ID);
					fRegion.setSelectedItem( region ) ;
					fCity.setText( x_City_Name );
	
					String oldAddress = fAddress1.getText();
					if( oldAddress==null || !oldAddress.startsWith( x_Address )){
						fAddress1.setText( x_Address );
					}
				}
				rs.close ();
				pstmt.close ();
				pstmt = null;
			}
			catch (Exception e)
			{
				log.log(Level.SEVERE, sql.toString(), e);
				try
				{
					if (pstmt != null)
						pstmt.close ();
				}
				catch (Exception pe)
				{
				}
				pstmt = null;
			}
		}
		
		
	}	//	action_PostalLookup
	
}	//	VLocationDialog
