/*
 * SysManagerStarter.java
 *
 * Created on 10 de agosto de 2004, 18:44
 */

package com.fenalco.servlets.sysmanager;

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

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.CompanyList;
import com.fenalco.entities.User;
import com.fenalco.entities.DataAccess;
import com.fenalco.entities.Province;
import com.fenalco.entities.City;
import com.fenalco.utilities.MessageBuilder;
import com.fenalco.utilities.lists.CompanyListViewSysManagerStart;

/**
 * 
 * @author andres
 * @version
 */
public class SysManagerStarter 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>.
	 * 
	 * -Crea un objeto de tipo <CODE>CompanyList</CODE> -Llama la función
	 * filter("new") -Crea un objeto de tipo <CODE>CompanyListView</CODE> con
	 * el objeto anterior -Manda en el response el anterio objeto (la vista)
	 * 
	 * -Redirecciona a administrador.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 = "";
            HttpSession session = request.getSession(false);
            
            if(request.getAttribute("message")!=null){
                message = (String)request.getAttribute("message");
            }

            try{
	        if( session == null || ( User )session.getAttribute( "user" ) == null || ( ( User )session.getAttribute( "user" ) ).getRoleId() != 1 ){
                    url = "/index.jsp";
                    message = MessageBuilder.buildMessage(15);
                }else{
                    // criterios de paginación
                    int page = 1;
                    int pageResults = 20;
                    int pages = 0; // numero total de páginas
                    int firstRow = 0; // numero del primero registro que se va a mostrar
                    int lastRow = 19; // numero del último registro que se va a mostrar
                    int total = 0; // numero total de resultados

                    
                    //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();
                        }

                        provincesList = DataAccess.getProvinces(countryId);
                        
                        if( combo.equals("country") ){
                            provinceId = -1;
                            citiesList = DataAccess.getCities(provinceId);
                            cityId = -1;
                            /*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") ){
                            citiesList = DataAccess.getCities(provinceId);
                            cityId = -1;
                            /*Enumeration en = citiesList.elements();
                            if( en.hasMoreElements() ){
                                cityId = ((City) en.nextElement()).getId();
                            }*/
                        }else{
                            citiesList = DataAccess.getCities(provinceId);
                        }
                        
                    }else{
                        provincesList = DataAccess.getProvinces(countryId);
                        citiesList = DataAccess.getCities(provinceId);
                    }
                    
                    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
                    
                    
                    CompanyList companyList = new CompanyList();
                    companyList.filterStatus(1);
                    companyList.filterByRegions(cityId, provinceId, countryId);
                    
                    
                    // aqui se efectua la paginación
                    if(request.getParameter("page")!=null){
                        try{
                            page = Integer.parseInt(request.getParameter("page"));
                        }catch(NumberFormatException nfe){
                            page = 1;
                        }    
                        page = (page < 1) ? 1 : page;
                        try{
                            pageResults = Integer.parseInt(request.getParameter("pageResults"));
                        }catch(NumberFormatException nfe){
                            pageResults = 20;
                        }
                        pageResults = (pageResults < 1) ? 20 : pageResults;
                    }

                    total = companyList.getCompanies().size();
                    pages = (int) Math.ceil((double) total / (double) pageResults);
                    if( page > pages ){
                            page = pages;
                    }
                    firstRow = (page - 1) * pageResults;
                    lastRow = page * pageResults;
                    firstRow = (firstRow < 0) ? 0 : firstRow;
                    if( lastRow > total ){
                            lastRow = total;
                    }

                    Vector temp = new Vector();
                    for( int i = 0; i < total; i++ ){
                            if( i >= firstRow && i <= lastRow - 1 ){
                                    temp.addElement(companyList.getCompanies().elementAt(i));
                            }
                    }

                    companyList.setCompanies(temp);

                    CompanyListViewSysManagerStart view = new CompanyListViewSysManagerStart(companyList);

                    request.setAttribute("view", view);

                    /// información de la paginacion
                    firstRow++; // para no arrancar desde 0
                    firstRow = (lastRow == 0) ? 0 : firstRow;
                    request.setAttribute("firstRow", firstRow + "");
                    request.setAttribute("lastRow", lastRow + "");
                    request.setAttribute("total", total + "");
                    request.setAttribute("page", page + "");
                    request.setAttribute("pages", pages + "");
                    request.setAttribute("pageResults", pageResults + "");

                    url = "/administrador/administrador.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.
	 */
	public String getServletInfo( )
	{
		return "Short description";
	}

}