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

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.logging.Level;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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.GridField;
import org.compiere.model.MCountry;
import org.compiere.model.MLocation;
import org.compiere.model.MRegion;
import org.compiere.util.CLogger;
import org.compiere.util.Ctx;
import org.compiere.util.DB;
import org.compiere.util.Env;
import org.compiere.util.Msg;
import org.compiere.util.WebSessionCtx;

import com.ampiere.dto.CodeValue;
import com.ampiere.util.Constants;
import com.ampiere.web.servlet.WWindowStatus;
import com.ampiere.web.struts.common.PopupBaseAction;

/**
 * @author Shinjirito
 *
 */
public class LocationAction 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("locationInit", "");
		LocationActionForm locationActionForm = (LocationActionForm)baseForm;
		if (locationActionForm != null) {
			int countryId = locationActionForm.getCountryId();
			String columnName = locationActionForm.getColumnName();
			String locationOption = locationActionForm.getLocationOption();
			locationActionForm.setLocationOption("");
			locationActionForm.setLocationId("");
			locationActionForm.setLocationName("");
		  	WebSessionCtx wsc = WebSessionCtx.get(request);
			WWindowStatus ws = WWindowStatus.get(request);
		  	if (wsc != null && columnName != null && ws != null) {
				GridField mField = ws.getCurTab().getField(columnName);
				MLocation location = null; 
				Object value = mField.getValue(); 
				if (value != null && value instanceof Integer) {
					location = new MLocation(wsc.ctx, ((Integer)value).intValue(), null);
				}
				if (location == null) {
					location = new MLocation(wsc.ctx, 0, null);
				}

				String postalId = locationActionForm.getPostalId();
				locationActionForm.setPostalId("");
				String fpostal = locationActionForm.getFpostal();
				String fpostalAdd = locationActionForm.getFpostalAdd();
				String faddress2 = locationActionForm.getFaddress2();
				String faddress3 = locationActionForm.getFaddress3();
				String faddress4 = locationActionForm.getFaddress4();

				//	Current Country
				MCountry.setDisplayLanguage(Env.getAD_Language(wsc.ctx));
				MCountry pCountry[] = MCountry.getCountries(wsc.ctx);
				ArrayList<CodeValue> countryList = new ArrayList<CodeValue>();
				for (int i = 0; i < pCountry.length; i++) {
					countryList.add(new CodeValue(Integer.toString(pCountry[i].getC_Country_ID()), pCountry[i].getName()));
				}
				locationActionForm.setCountryList(countryList);

				MCountry country = null;
				if (countryId != 0) {
					country = MCountry.get(wsc.ctx, countryId);
		  		}
				if (country != null) {
					location.setCountry(country);
				}

		  		if ("save".equals(locationOption)) {
		  			location.setAddress1(locationActionForm.getFaddress1());
		  			location.setAddress2(locationActionForm.getFaddress2());
		  			location.setAddress3(locationActionForm.getFaddress3());
		  			location.setAddress4(locationActionForm.getFaddress4());
		  			location.setCity(locationActionForm.getFcity());
		  			location.setPostal(locationActionForm.getFpostal());
		  			location.setPostal_Add(locationActionForm.getFpostalAdd());
		  			//  Country/Region
		  			location.setCountry(country);
		  			if (location.getCountry().isHasRegion())
		  			{
		  				MRegion region = MRegion.get(wsc.ctx, Integer.parseInt(locationActionForm.getRegionSelected()));
		  				location.setRegion(region);
		  			} else {
		  				location.setC_Region_ID(0);
		  			}

		  			//	Save chnages
		  			location.save();
					request.setAttribute("locationInit", "close");
					locationActionForm.setLocationId(Integer.toString(location.getC_Location_ID()));
					locationActionForm.setLocationName(location.toString());
		  		} else {
					countryId = location.getCountry().getC_Country_ID();
					locationActionForm.setCountryId(countryId);
					locationActionForm.setAddressLinesLocalReverse(location.getCountry().isAddressLinesLocalReverse());
					request.setAttribute("addressLinesLocalReverse", (location.getCountry().isAddressLinesLocalReverse() ? "true" : "false"));
	
					// Current Region
					MRegion pRegion[] = MRegion.getRegions(wsc.ctx, countryId);
					ArrayList<CodeValue> regionList = new ArrayList<CodeValue>();
					for (int i = 0; i < pRegion.length; i++) {
						regionList.add(new CodeValue(Integer.toString(pRegion[i].getC_Region_ID()), pRegion[i].getName()));
					}
					locationActionForm.setRegionList(regionList);
	
					if (location.getC_Location_ID() != 0)
					{
						locationActionForm.setFaddress1(location.getAddress1());
						locationActionForm.setFaddress2(location.getAddress2());
						locationActionForm.setFaddress3(location.getAddress3());
						locationActionForm.setFaddress4(location.getAddress4());
						locationActionForm.setFcity(location.getCity());
						locationActionForm.setFpostal(location.getPostal());
	
						locationActionForm.setFpostalAdd(location.getPostal_Add());
						if (location.getCountry().isHasRegion() && location.getRegion() != null)
						{
							locationActionForm.setRegionSelected(Integer.toString(location.getRegion().getC_Region_ID()));
						}
					}
					locationActionForm.setCountrySelected(Integer.toString(countryId));
					setLocationFlags(location.getCountry(), request);
	
					// Initialize labels
					if (location.getC_Location_ID() == 0) {
						locationActionForm.setTitle(Msg.translate(wsc.ctx, "LocationNew"));
					} else {
						locationActionForm.setTitle(Msg.translate(wsc.ctx, "LocationUpdate"));
					}
					locationActionForm.setCloseBtnTitle(Msg.translate(wsc.ctx, "Cancel"));
					locationActionForm.setSubmitBtnTitle(Msg.translate(wsc.ctx, "OK"));
					locationActionForm.setLaddress1(Msg.translate(wsc.ctx, "Address") + " 1");
					locationActionForm.setLaddress2(Msg.translate(wsc.ctx, "Address") + " 2");
					locationActionForm.setLaddress3(Msg.translate(wsc.ctx, "Address") + " 3");
					locationActionForm.setLaddress4(Msg.translate(wsc.ctx, "Address") + " 4");
					locationActionForm.setLcity(Msg.translate(wsc.ctx, "City"));
					locationActionForm.setLcountry(Msg.translate(wsc.ctx, "Country"));
					locationActionForm.setLregion(Msg.translate(wsc.ctx, "Region"));
					if (location.getCountry().isHasRegion()) {
						locationActionForm.setLregion(location.getCountry().getRegionName());	//	name for region
					}
					locationActionForm.setLpostal(Msg.translate(wsc.ctx, "Postal"));
					locationActionForm.setLpostalAdd(Msg.translate(wsc.ctx, "PostalAdd"));
					locationActionForm.setLpostalLookup(Msg.translate(wsc.ctx, "PostalLookup"));
	
					if ("change".equals(locationOption)) {
						// Postal lookup
						locationActionForm.setFpostal(fpostal);
						locationActionForm.setFpostalAdd(fpostalAdd);
						locationActionForm.setFaddress2(faddress2);
						locationActionForm.setFaddress3(faddress3);
						locationActionForm.setFaddress4(faddress4);
						if (! action_PostalLookup(wsc.ctx, postalId, fpostal, fpostalAdd, locationActionForm, location)) {
							request.setAttribute("locationInit", "popup");
						}
					}
		  		}
		  	}
		}

		return mapping.findForward("success");
	}

	/**
	 *  Jirimuto Modified 2005/11/20
	 */
	private boolean action_PostalLookup(Ctx ctx, String postalId, String fPostal, String fPostalAdd, LocationActionForm locationActionForm, MLocation location)
	{
		PreparedStatement pstmt = null;
		StringBuffer sql = null;
		if (postalId != null && postalId.length() > 0) {
			Integer id = Integer.parseInt(postalId);

			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=" + 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);
					locationActionForm.setFpostal(x_Postal);
					locationActionForm.setFpostalAdd(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(ctx, c_Region_ID);
					locationActionForm.setRegionSelected(Integer.toString(region.getC_Region_ID()));
					locationActionForm.setFcity( x_City_Name );
	
					String oldAddress = locationActionForm.getFaddress1();
					if( oldAddress==null || !oldAddress.startsWith( x_Address )){
						locationActionForm.setFaddress1( x_Address );
					}
				}
				rs.close ();
				pstmt.close ();
				pstmt = null;
				return true;
			}
			catch (Exception e)
			{
				log.log(Level.SEVERE, sql.toString(), e);
				try
				{
					if (pstmt != null)
						pstmt.close ();
				}
				catch (Exception pe)
				{
				}
				pstmt = null;
			}
		}

		/*********************************************************************/
		fPostal = (fPostal.trim());
		fPostalAdd = fPostalAdd.trim();

		String value = fPostal + fPostalAdd;

		int count = 0;
		sql = new StringBuffer ("SELECT COUNT(X_POSTAL_ID) " 
		    + " FROM X_POSTAL"
			+ " WHERE IsActive='Y'" +
			" AND C_COUNTRY_ID=" + 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=" + 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(ctx, c_Region_ID);
					locationActionForm.setRegionSelected(Integer.toString(region.getC_Region_ID()));
					locationActionForm.setFcity( x_City_Name );
	
					String oldAddress = locationActionForm.getFaddress1();
					if( oldAddress==null || !oldAddress.startsWith( x_Address )){
						locationActionForm.setFaddress1( 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;
			}

			return true;
		}

		return false;
	}	//	action_PostalLookup

	/**
	 * @param country
	 * @param request
	 */
	private void setLocationFlags(MCountry country, HttpServletRequest request) {
		request.setAttribute("city", "false");
		request.setAttribute("postal", "false");
		request.setAttribute("postalAdd", "false");
		request.setAttribute("region", "false");

		//  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@
		}
		StringTokenizer st = new StringTokenizer(ds, "@", false);
		while (st.hasMoreTokens())
		{
			String s = st.nextToken();
			if (s.startsWith("C"))
				request.setAttribute("city", "true");
			else if (s.startsWith("P"))
				request.setAttribute("postal", "true");
			else if (s.startsWith("A"))
				request.setAttribute("postalAdd", "true");
			else if (s.startsWith("R") && country.isHasRegion())
				request.setAttribute("region", "true");
		}
	}
}
