/*
 * CompanyListView.java
 *
 * Created on 10 de agosto de 2004, 18: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.Province;
import com.fenalco.entities.ShopKeeperList;
import com.fenalco.entities.SupplierList;
import com.fenalco.entities.User;
import com.fenalco.utilities.MessageBuilder;
import com.fenalco.utilities.lists.ShopKeeperListViewSysManager;
import com.fenalco.utilities.lists.SupplierListViewSysManager;

/**
 * 
 * @author andres
 * @version
 */
public class CompanyListView 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>.
	 * 
	 * Recibe el parámetro companyType que indica la clase de empresas a mostrar
	 * 
	 * -Dependiendo del valor de companyType crea: 1)-Crea un objeto de tipo
	 * <CODE>SupplierList</CODE> -Crea un objeto de tipo <CODE>
	 * SupplierListViewSysManager</CODE> con el objeto anterior 2)-Crea un
	 * objeto de tipo <CODE>ShopKeeperList</CODE> -Crea un objeto de tipo
	 * <CODE>ShopKeeperListViewSysManager</CODE> con el objeto anterior
	 * 
	 * -Manda en el response el anterior objeto (la vista) -Redirecciona a
	 * listaempresas.jsp
	 * 
	 * @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 = "";
		if( (String) request.getAttribute("message") != null )
		{
			message = (String) request.getAttribute("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
			{
	
				int companyType = 1;
	
				//Carga una lista de proveedores o de minoristas según sea el caso
				if( request.getParameter("companyType") != null )
				{
					companyType = Integer.parseInt(request
							.getParameter("companyType"));
				}
	
				//Inicio de los combos
	
				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);
					citiesList = DataAccess.getCities(provinceId);
				}
	
				request.setAttribute("companyType", (new Integer(companyType))
						.toString());
				request.setAttribute("countryId", new Integer(countryId));
				request.setAttribute("provinceId", new Integer(provinceId));
				request.setAttribute("cityId", new Integer(cityId));
	
				request.setAttribute("countriesList", countriesList);
				request.setAttribute("provincesList", provincesList);
				request.setAttribute("citiesList", citiesList);
	
				//Fin de los combos
	
				if( companyType == 1 )
				{
					ShopKeeperList shopKeeperList = new ShopKeeperList();
					shopKeeperList.filterByCity(cityId);
					ShopKeeperListViewSysManager view = new ShopKeeperListViewSysManager(
							shopKeeperList);
					request.setAttribute("view", view);
				}
				else
				{
					SupplierList supplierList = new SupplierList();
					supplierList.filterByCity(cityId);
					SupplierListViewSysManager view = new SupplierListViewSysManager(
							supplierList);
					request.setAttribute("view", view);
				}
	
				url = "/administrador/listaempresas.jsp";
			}
	    }
	    catch( Exception 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.
	 */
	public String getServletInfo( )
	{
		return "Short description";
	}

}