/*
 * LogisticOperatorListListener.java
 *
 * Created on 15 de septiembre de 2004, 15:19
 */

package com.fenalco.servlets.sysmanager;

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.DataAccess;
import com.fenalco.entities.LogisticOperator;
import com.fenalco.entities.Province;
import com.fenalco.entities.User;
import com.fenalco.utilities.MessageBuilder;

/**
 * 
 * @author Juan Ernesto Peña Kaltekis
 * @version
 */
public class LogisticOperatorListListener extends HttpServlet
{

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

	}

	/**
	 * Destruye el servlet.
	 */
	public void destroy( )
	{

	}

	/**
	 * Procesa las peticiones de los métodos HTTP <code>GET</code> y
	 * <code>POST</code>.
	 * 
	 * @param request
	 *            petición al servlet
	 * @param response
	 *            respuesta del servlet
	 */
	protected void processRequest( HttpServletRequest request,
			HttpServletResponse response ) throws ServletException, IOException
	{

		String url = "";
		String message = "";
		HttpSession session = request.getSession(false);
	    try
	    {
	        if( session == null || ( User )session.getAttribute( "user" ) == null || ( ( User )session.getAttribute( "user" ) ).getRoleId() != 1 )
			{
				url = "/index.jsp";
				message = MessageBuilder.buildMessage(15);
			}
			else
			{
	
				String operationType = request.getParameter("operationType");
	
				if( operationType.equals("new") )
				{
					Vector countriesList = DataAccess.getCountries();
					Vector provincesList = new Vector();
					Vector citiesList = new Vector();
	
					int countryId = 1;
					int provinceId = 1;
					int cityId = 1;
	
					String combo = request.getParameter("combo");
					if( combo != null )
					{
	
						countryId = (new Integer(request.getParameter("country")))
								.intValue();
						if( request.getParameter("province") != null )
						{
							provinceId = (new Integer(request
									.getParameter("province"))).intValue();
						}
						if( request.getParameter("city") != null )
						{
							cityId = (new Integer(request.getParameter("city")))
									.intValue();
						}
	
						if( combo.equals("country") )
						{
							provincesList = DataAccess.getProvinces(countryId);
							Enumeration en = provincesList.elements();
							if( en.hasMoreElements() )
							{
								provinceId = ((Province) en.nextElement()).getId();
								citiesList = DataAccess.getCities(provinceId);
								en = citiesList.elements();
								if( en.hasMoreElements() )
								{
									cityId = ((City) en.nextElement()).getId();
								}
							}
						}
						else
							if( combo.equals("province") )
							{
								provincesList = DataAccess.getProvinces(countryId);
								citiesList = DataAccess.getCities(provinceId);
								Enumeration en = citiesList.elements();
								if( en.hasMoreElements() )
								{
									cityId = ((City) en.nextElement()).getId();
								}
							}
							else
							{
								provincesList = DataAccess.getProvinces(countryId);
								citiesList = DataAccess.getCities(provinceId);
							}
					}
					else
					{
						provincesList = DataAccess.getProvinces(countryId);
						Enumeration en = provincesList.elements();
						provinceId = ((Province) en.nextElement()).getId();
						citiesList = DataAccess.getCities(provinceId);
						en = citiesList.elements();
						cityId = ((City) en.nextElement()).getId();
					}
	
					String id = request.getParameter("key");
					String name = request.getParameter("name");
					String address = request.getParameter("address");
					String contact = request.getParameter("contact");
					String phoneNumber = request.getParameter("phoneNumber");
					String email = request.getParameter("email");
	
					if( name == null )
					{
						name = "";
					}
					if( address == null )
					{
						address = "";
					}
					if( contact == null )
					{
						contact = "";
					}
					if( phoneNumber == null )
					{
						phoneNumber = "";
					}
					if( email == null )
					{
						email = "";
					}
	
					request.setAttribute("key", id);
					request.setAttribute("name", name);
					request.setAttribute("address", address);
					request.setAttribute("contact", contact);
					request.setAttribute("phoneNumber", phoneNumber);
					request.setAttribute("email", email);
	
					request.setAttribute("countryId", new Integer(countryId));
					request.setAttribute("cityId", new Integer(cityId));
					request.setAttribute("provinceId", new Integer(provinceId));
	
					request.setAttribute("citiesList", citiesList);
					request.setAttribute("countriesList", countriesList);
					request.setAttribute("provincesList", provincesList);
	
					url = "/administrador/nuevooperadorlogistico.jsp";
				}
				else
					if( operationType.equals("delete") )
					{
						url = "/administrador/administraroperadorlogistico";
					}
					else
						if( operationType.equals("update") )
						{
	
							Vector countriesList = DataAccess.getCountries();
							Vector provincesList = new Vector();
							Vector citiesList = new Vector();
	
							int countryId = 1;
							int provinceId = 1;
							int cityId = 1;
	
							String id = "";
							String name = "";
							String address = "";
							String contact = "";
							String phoneNumber = "";
							String email = "";
	
							String combo = request.getParameter("combo");
							if( combo != null )
							{
	
								countryId = (new Integer(request
										.getParameter("country"))).intValue();
								if( request.getParameter("province") != null )
								{
									provinceId = (new Integer(request
											.getParameter("province"))).intValue();
								}
								if( request.getParameter("city") != null )
								{
									cityId = (new Integer(request
											.getParameter("city"))).intValue();
								}
	
								if( combo.equals("country") )
								{
									provincesList = DataAccess
											.getProvinces(countryId);
									Enumeration en = provincesList.elements();
									if( en.hasMoreElements() )
									{
										provinceId = ((Province) en.nextElement())
												.getId();
										citiesList = DataAccess
												.getCities(provinceId);
										en = citiesList.elements();
										if( en.hasMoreElements() )
										{
											cityId = ((City) en.nextElement())
													.getId();
										}
									}
								}
								else
									if( combo.equals("province") )
									{
										provincesList = DataAccess
												.getProvinces(countryId);
										citiesList = DataAccess
												.getCities(provinceId);
										Enumeration en = citiesList.elements();
										if( en.hasMoreElements() )
										{
											cityId = ((City) en.nextElement())
													.getId();
										}
									}
									else
									{
										provincesList = DataAccess
												.getProvinces(countryId);
										citiesList = DataAccess
												.getCities(provinceId);
									}
	
								id = request.getParameter("key");
								name = request.getParameter("name");
								address = request.getParameter("address");
								contact = request.getParameter("contact");
								phoneNumber = request.getParameter("phoneNumber");
								email = request.getParameter("email");
	
							}
							else
							{
								int operatorId = Integer.parseInt(request
										.getParameter("key"));
								LogisticOperator logisticOperator = new LogisticOperator(
										operatorId);
	
								id = request.getParameter("key");
								name = logisticOperator.getName();
								address = logisticOperator.getAddress();
								contact = logisticOperator.getContact();
								phoneNumber = logisticOperator.getPhoneNumber();
								email = logisticOperator.getEmail();
								cityId = logisticOperator.getCityId();
								City city = new City(cityId);
								provinceId = city.getProvince();
								Province province = new Province(provinceId);
								countryId = province.getCountry();
	
								provincesList = DataAccess.getProvinces(countryId);
								citiesList = DataAccess.getCities(provinceId);
							}
	
							if( name == null )
							{
								name = "";
							}
							if( address == null )
							{
								address = "";
							}
							if( contact == null )
							{
								contact = "";
							}
							if( phoneNumber == null )
							{
								phoneNumber = "";
							}
							if( email == null )
							{
								email = "";
							}
	
							request.setAttribute("key", id);
							request.setAttribute("name", name);
							request.setAttribute("address", address);
							request.setAttribute("contact", contact);
							request.setAttribute("phoneNumber", phoneNumber);
							request.setAttribute("email", email);
	
							request.setAttribute("countryId",
									new Integer(countryId));
							request.setAttribute("cityId", new Integer(cityId));
							request.setAttribute("provinceId", new Integer(
									provinceId));
	
							request.setAttribute("citiesList", citiesList);
							request.setAttribute("countriesList", countriesList);
							request.setAttribute("provincesList", provincesList);
	
							//request.setAttribute("logisticOperator",
							// logisticOperator);
							url = "/administrador/modificaroperadorlogistico.jsp";
						}
			}
	    }
	    catch( Exception e )
	    {
                System.out.println("Error-> "+e);
	        url="/logout";
	        message = MessageBuilder.buildMessage(15);
	    }

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

	/**
	 * Maneja el método HTTP <code>GET</code>
	 * 
	 * @param request
	 *            petición al servlet
	 * @param response
	 *            respuesta del servlet
	 */
	protected void doGet( HttpServletRequest request,
			HttpServletResponse response ) throws ServletException, IOException
	{
		processRequest(request, response);
	}

	/**
	 * Maneja el método HTTP <code>POST</code>
	 * 
	 * @param request
	 *            petición al servlet
	 * @param response
	 *            respuesta del servlet
	 */
	protected void doPost( HttpServletRequest request,
			HttpServletResponse response ) throws ServletException, IOException
	{
		processRequest(request, response);
	}

	/**
	 * Retorna una corta descripción del servlet servlet.
	 */
	public String getServletInfo( )
	{
		return "Short description";
	}

}