/*
 * StoresListener.java
 *
 * Created on 10 de agosto de 2004, 18:00
 */

package com.fenalco.servlets.shopkeeper;

import java.io.IOException;
import java.util.Enumeration;
import java.util.Vector;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.fenalco.entities.City;
import com.fenalco.entities.Company;
import com.fenalco.entities.DataAccess;
import com.fenalco.entities.Province;
import com.fenalco.entities.Store;
import com.fenalco.entities.User;
import com.fenalco.utilities.MessageBuilder;

/**
 * Este servlet se encarga de recibir la acción que se ejecuta en el listado de
 * los establecimientos del minorista y redireccionar a donde sea necesario de
 * acuerdo con la operación seleccionda por el minorista
 * 
 * @author Mario Linares Vásquez
 *  
 */
public class StoresListener extends HttpServlet
{

	/**
	 * Inicializa el servlet.
	 * 
	 * @param config
	 * @throws ServletException
	 */
	public void init( ServletConfig config ) throws ServletException
	{
		super.init(config);

	}

	/**
	 * Destructor de servlet.
	 */
	public void destroy( )
	{

	}

	/**
	 * Recibe un parámetro llamado <CODE>operationType</CODE> que puede ser:
	 *  - new - delete - update
	 * 
	 * dependiendo del valor del parámetro hace lo siguiente:
	 *  - new: carga los listados de país, departamento, ciudad y barrio y los
	 * almacena en el request de la siguiente forma:
	 *  - citiesList: lista de ciudades. Esta lista se obtiene llamando al
	 * método <CODE>getCities</CODE> de la <CODE>clase DataAccess</CODE>.
	 *  - countriesList: lista de paises. Esta lista se obtiene llamando al
	 * método <CODE>getCountries</CODE> de la clase <CODE>DataAccess</CODE>
	 *  - provincesList: lista de departamentos. esta lista se obtiene llamando
	 * al método <CODE>getProvinces</CODE> de la clase <CODE>DataAccess
	 * </CODE>
	 *  - neighbourhoodsList. lista de barrios. Esta lista se obtiene llamando
	 * al método <CODE>getNeighbourhoods</CODE> de la clase <CODE>DataAccess
	 * </CODE>
	 * 
	 * luego redirecciona a /minorista/nuevoestablecimiento.jsp
	 *  - update: recibe un parámetro llamado id, con el cual debe crear un
	 * objeto de tipo Store pasandole ese parámetro para que lo cargue de la
	 * base de datos
	 * 
	 * Además carga la información de ubicación geográfica descrita
	 * anteriormente
	 * 
	 * Adiciona estos listados al request Adiciona el objeto Store al reques
	 * 
	 * redirecciona a /minorista/modificarestablecimiento.jsp
	 * 
	 * @param request
	 *            servlet request
	 * @param response
	 *            servlet response
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void processRequest( HttpServletRequest request,
			HttpServletResponse response ) throws ServletException, IOException
	{

		String url = "/minorista/misestablecimientos";
		String message = "";
        HttpSession session = request.getSession( false );

	    try
	    {
	        if( session != null && ( User )session.getAttribute( "user" ) != null && ( ( User )session.getAttribute( "user" ) ).getRoleId() == 3 )
			{
	
				String operationType = request.getParameter("operationType");
				String operationType2 = request.getParameter("operationType2");
				User user = (User) request.getSession().getAttribute("user");
				int shopKeeperId = user.getCompanyId();
				//--------------------------------------------------------------------------------
				int countryId = 1;
				int provinceId = 1;
				int cityId = 1;
				int neighbourhoodId = 1;
				String name = "";
				String address = "";
				String GLN = "";
				String stratum = "";
				String street = "";
				String avenue = "";
				String avenueOrientation = "";
				String streetOrientation = "";
				String phoneNumber1 = "";
				String phoneNumber2 = "";
				String contact1 = "";
				String contact2 = "";
				String storeArea = "";
				String paymentPoints = "";
				String wareHouseArea = "";
				Vector countriesList = DataAccess.getValidCountries2();
				Vector provincesList = null;
				Vector citiesList = null;
				Vector neighbourhoodsList = null;
				//---------------------------------------------------------------------------------------------------------------
	
				if( operationType.equals("new") || operationType.equals("update") )
				{
					if( operationType2 == null )
					{
						if( operationType.equals("new") )
						{
							url = "/minorista/nuevoestablecimiento.jsp";
							int stores = DataAccess.getStoresNumber(shopKeeperId);
							if( stores < DataAccess.getMaxStoresNumber() )
							{
								if( stores == 0 )
								{
									//cargar datos de la empresa
									Company company = new Company(shopKeeperId);
									name = company.getCommercialName();
									address = company.getAddress();
									phoneNumber1 = company.getPhoneNumber1();
									phoneNumber2 = company.getPhoneNumber2();
									contact1 = company.getContact1();
									contact2 = company.getContact2();
	
									int city = company.getCityId();
									int province = DataAccess.getCityProvince(city);
									int country = DataAccess
											.getProvinceCountry(province);
	
									provincesList = DataAccess
											.getValidProvinces2(country);
									citiesList = DataAccess
											.getValidCities(province);
									neighbourhoodsList = DataAccess
											.getNeighbourhoods(city);
	
									//                                        System.out.println("paises-->"+countriesList);
									//                                        System.out.println("provincias-->"+provincesList);
									//                                        System.out.println("ciudades-->"+citiesList);
									//                                        System.out.println("barrios-->"+neighbourhoodsList);
	
									countryId = new Integer(DataAccess
											.getProvinceCountry(province))
											.intValue();
									provinceId = new Integer(province).intValue();
									cityId = new Integer(city).intValue();
									//
								}
								else
								{
	
									provincesList = DataAccess
											.getValidProvinces2(countryId);
									Enumeration en = provincesList.elements();
									provinceId = ((Province) en.nextElement())
											.getId();
									citiesList = DataAccess
											.getValidCities(provinceId);
									en = citiesList.elements();
									cityId = ((City) en.nextElement()).getId();
									neighbourhoodsList = DataAccess
											.getNeighbourhoods(cityId);
	
								}
							}
							else
							{
								url = "/minorista/misestablecimientos.jsp";
								message = MessageBuilder.buildMessage(24);
							}
	
						}
						else
							if( operationType.equals("update") )
							{
								url = "/minorista/actualizarestablecimiento.jsp";
								String id = request.getParameter("id");
								request.setAttribute("id", id);
	
								Store store = new Store(Integer.parseInt(id));
	
								name = store.getName();
								address = store.getAddress();
								GLN = store.getGln();
								stratum = Integer.toString((store.getStratum()));
								street = Integer.toString((store.getStreet()));
								avenue = Integer.toString((store.getAvenue()));
								avenueOrientation = store.getAvenueOrientation();
								streetOrientation = store.getStreetOrientation();
	
								phoneNumber1 = store.getPhoneNumber1();
								phoneNumber2 = store.getPhoneNumber2();
								contact1 = store.getContact1();
								contact2 = store.getContact2();
	
								storeArea = Double.toString(store.getStoreArea());
								paymentPoints = Integer.toString(store
										.getPayPlaces());
								wareHouseArea = Double.toString(store
										.getWareHouseArea());
	
								neighbourhoodId = store.getNeighbourhood();
								cityId = DataAccess
										.getNeighbourhoodCity(neighbourhoodId);
								provinceId = DataAccess.getCityProvince(cityId);
								countryId = DataAccess
										.getProvinceCountry(provinceId);
	
								provincesList = DataAccess
										.getValidProvinces2(countryId);
								citiesList = DataAccess.getValidCities(provinceId);
								neighbourhoodsList = DataAccess
										.getNeighbourhoods(cityId);
							}
					}
					else
					{// recargar página (operationType2 != null)
						//cargar datos de la forma
	
						name = request.getParameter("name");
						address = request.getParameter("address");
						GLN = request.getParameter("GLN");
						stratum = request.getParameter("stratum");
						street = request.getParameter("street");
						avenue = request.getParameter("avenue");
						avenueOrientation = request
								.getParameter("avenueOrientation");
						streetOrientation = request
								.getParameter("streetOrientation");
	
						phoneNumber1 = request.getParameter("phoneNumber1");
						phoneNumber2 = request.getParameter("phoneNumber2");
						contact1 = request.getParameter("contact1");
						contact2 = request.getParameter("contact2");
	
						storeArea = request.getParameter("storeArea");
						paymentPoints = request.getParameter("paymentPoints");
						wareHouseArea = request.getParameter("wareHouseArea");
	
						neighbourhoodId = Integer.parseInt(request
								.getParameter("neighbourhood"));
						cityId = Integer.parseInt(request.getParameter("city"));
						provinceId = Integer.parseInt(request
								.getParameter("province"));
						countryId = Integer.parseInt(request
								.getParameter("country"));
						provincesList = DataAccess.getValidProvinces2(countryId);
						citiesList = DataAccess.getValidCities(provinceId);
						neighbourhoodsList = DataAccess.getNeighbourhoods(cityId);
	
						//---------------------------------------
						//cargar datos de listas
						String combo = request.getParameter("combo");
						if( combo != null )
						{
							countryId = (new Integer(request
									.getParameter("country"))).intValue();
							provinceId = (new Integer(request
									.getParameter("province"))).intValue();
							cityId = (new Integer(request.getParameter("city")))
									.intValue();
							String temp = request.getParameter("neighbourhood");
							if( temp != null )
							{
								neighbourhoodId = (new Integer(temp)).intValue();
							}
	
							provincesList = DataAccess
									.getValidProvinces2(countryId);
							citiesList = DataAccess.getValidCities(provinceId);
							neighbourhoodsList = DataAccess
									.getNeighbourhoods(cityId);
	
							if( combo.equals("country") )
							{
	
								Enumeration en = provincesList.elements();
								provinceId = ((Province) en.nextElement()).getId();
								citiesList = DataAccess.getValidCities(provinceId);
								en = citiesList.elements();
								cityId = ((City) en.nextElement()).getId();
								neighbourhoodsList = DataAccess
										.getNeighbourhoods(cityId);
	
							}
							else
								if( combo.equals("province") )
								{
	
									Enumeration en = citiesList.elements();
									cityId = ((City) en.nextElement()).getId();
									neighbourhoodsList = DataAccess
											.getNeighbourhoods(cityId);
								}
	
						}
	
						if( operationType.equals("new") )
						{
							url = "/minorista/nuevoestablecimiento.jsp";
						}
						else
							if( operationType.equals("update") )
							{
								url = "/minorista/actualizarestablecimiento.jsp";
							}
	
						//listas
						//finaliza if de recarga
					}
	
					//----------------------------------------------------------------
					// verificar nulls
					if( name == null )
					{
						name = "";
					}
					if( address == null )
					{
						address = "";
					}
					if( GLN == null )
					{
						GLN = "";
					}
					if( stratum == null )
					{
						stratum = "";
					}
					if( street == null )
					{
						street = "";
					}
					if( avenue == null )
					{
						avenue = "";
					}
					if( avenueOrientation == null )
					{
						avenueOrientation = "";
					}
					if( streetOrientation == null )
					{
						streetOrientation = "";
					}
	
					if( storeArea == null )
					{
						storeArea = "";
					}
					if( paymentPoints == null )
					{
						paymentPoints = "";
					}
					if( wareHouseArea == null )
					{
						wareHouseArea = "";
					}
	
					if( phoneNumber1 == null )
					{
						phoneNumber1 = "";
					}
					if( phoneNumber2 == null )
					{
						phoneNumber2 = "";
					}
					if( contact1 == null )
					{
						contact1 = "";
					}
					if( contact2 == null )
					{
						contact2 = "";
					}
					//----------------------------------------------------------------
					// fijar atributos
					request.setAttribute("countryId", new Integer(countryId));
					request.setAttribute("cityId", new Integer(cityId));
					request.setAttribute("provinceId", new Integer(provinceId));
					request.setAttribute("neighbourhoodId", new Integer(
							neighbourhoodId));
	
					request.setAttribute("citiesList", citiesList);
					request.setAttribute("countriesList", countriesList);
					request.setAttribute("provincesList", provincesList);
					request.setAttribute("neighbourhoodsList", neighbourhoodsList);
	
					request.setAttribute("name", name);
					request.setAttribute("address", address);
					request.setAttribute("contact1", contact1);
					request.setAttribute("contact2", contact2);
					request.setAttribute("phoneNumber1", phoneNumber1);
					request.setAttribute("phoneNumber2", phoneNumber2);
	
					request.setAttribute("GLN", GLN);
					request.setAttribute("stratum", stratum);
					request.setAttribute("street", street);
					request.setAttribute("avenue", avenue);
					request.setAttribute("avenueOrientation", avenueOrientation);
					request.setAttribute("street", street);
					request.setAttribute("streetOrientation", streetOrientation);
					request.setAttribute("storeArea", storeArea);
					request.setAttribute("paymentPoints", paymentPoints);
					request.setAttribute("wareHouseArea", wareHouseArea);
	
					// atributos
	
				}
	
				else
					if( operationType.equals("delete") )
					{
						url = "/minorista/administrarestablecimientos?operationType=delete";
					}
	
			}
			else
			{
				message = MessageBuilder.buildMessage(15);
				url = "/index.jsp";
			}
	    }
	    catch( Exception e )
	    {
	        url="/logout";
	        message = MessageBuilder.buildMessage(15);
	    }

		request.setAttribute("message", message);
		RequestDispatcher dispatcher = getServletContext()
				.getRequestDispatcher(url);
		dispatcher.forward(request, response);
	}

	/**
	 * Procesa el método HTTP <code>GET</code>.
	 * 
	 * @param request
	 *            servlet request
	 * @param response
	 *            servlet response
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void doGet( HttpServletRequest request,
			HttpServletResponse response ) throws ServletException, IOException
	{
		processRequest(request, response);
	}

	/**
	 * Procesa el método HTTP <code>POST</code>.
	 * 
	 * @param request
	 *            servlet request
	 * @param response
	 *            servlet response
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void doPost( HttpServletRequest request,
			HttpServletResponse response ) throws ServletException, IOException
	{
		processRequest(request, response);
	}

	/**
	 * Retorna una breve descripción de el servlet.
	 * 
	 * @return
	 */
	public String getServletInfo( )
	{
		return "Short description";
	}

}