/*
 * LoadRegistryData.java
 *
 * Created on 13 de agosto de 2004, 13:20
 */

package com.fenalco.servlets;

import java.io.IOException;
import java.util.Enumeration;
import java.util.Hashtable;
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 com.fenalco.entities.City;
import com.fenalco.entities.DataAccess;
import com.fenalco.entities.PositionList;
import com.fenalco.entities.Province;



/**
 * Carga los datos necesarios para armar el formulario de registro
 * @author Mario Linares Vásquez
 */

public class LoadRegistryData extends HttpServlet {
    
    /** Inicializa el servlet.
     */
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        
    }
    
    /** Método destructor.
     */
    public void destroy() {
        
    }
    
    /**
     * Este servlet se encarga de cargar toda la información que se necesita en el formulario
     * de registro de nuevos usuarios, esta información se almacena en el request como
     * atributos y es la siguiente:
     *
     * - sectorList: Lista de sectores económicos con la cual se construye el selector
     *  sector. Esta lista se obtiene llamando al método <CODE>getSectors</CODE> de la clase
     *  <CODE>DataAccess</CODE>
     *
     * - companyTypes: lista de tipos de compañias. Esta lista se obtiene llamando
     *   al método <CODE>getCompanyTypes</CODE> de la clase <CODE>DataAccess</CODE>
     *
     * - 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>
     *
     * - ciiuList. Lista de ciiu. Esta lista se obtiene llamando al método
     *   <CODE>getCiiu</CODE> de la clase <CODE>DataAccess</CODE>
     *
     * Nota: todos los métodos de la clase <CODE>DataAccess</CODE> son estáticos, por lo tanto
     * no hay que instanciar esta clase.
     *
     * este servlet también recibe los siguientes datos que se usarán para enviarselos
     * de nuevo al jsp:
     *
     * - type
     * - socialname
     * - commercialName
     * - description
     * - companyId
     * - sector
     * - address
     * - phoneNumber1
     * - phonbeNumber2
     * - contact1
     * - contact2
     * - fax
     * - email
     * - fenalcoNumber
     * - ciiu
     * - country
     * - province
     * - city
     * - neighbourhood
     * - combo: para saber que selecciono el usuario en la ubicación geográfica
     *
     * - login
     * - passwd
     * - passwd2
     * - firstName
     * - lastName
     * - position
     * - userEmail
     * - idNumber
     * - GLN
     * 
     *
     * estos parametros simplemente se reciben y se envian de nuevo al jsp
     * @param request servlet request
     * @param response servlet response
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        
      String url = new String("/registro.jsp");
      

      Vector countriesList = DataAccess.getValidCountries();
      Vector provincesList = null;
      Vector citiesList = null;
      Vector neighbourhoodsList = null;
      String GLN  = request.getParameter("GLN");
      String type = request.getParameter("type");
      
      int countryId = 1;
      int provinceId = 1;
      int cityId =1;
      int neighbourhoodId = 1;
      int positionId = 1;
      
      
      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.getValidProvinces(countryId);
          citiesList = DataAccess.getCities(provinceId);
          neighbourhoodsList = DataAccess.getNeighbourhoods(cityId);
      
          if(combo.equals("country")){
              
              Enumeration en = provincesList.elements();
              provinceId = ((Province)en.nextElement()).getId();
              citiesList = DataAccess.getCities( provinceId);
              en = citiesList.elements();
              cityId  =  ((City)en.nextElement()).getId();
              neighbourhoodsList = DataAccess.getNeighbourhoods(cityId);
              
          }
          else if(combo.equals("province")){
          //    citiesList = DataAccess.getCities( provinceId);
              Enumeration en = citiesList.elements();
              cityId  =   ((City)en.nextElement()).getId();
              neighbourhoodsList = DataAccess.getNeighbourhoods(cityId);
          }
          
          if(request.getParameter("type").equals("2")){
                request.setAttribute("showGLN","true");  
          }
          else{
               request.setAttribute("showGLN","false");
               GLN = "";
          }
          
          
      }
      else{
         provincesList = DataAccess.getValidProvinces(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);
      }
      
      //tipo de empresa
      int typeId = 1;
      String temp = request.getParameter("type");
       if(temp != null){
          typeId = ( new Integer(temp)).intValue();
      }
      //sector
      int sectorId = 1;
       temp = request.getParameter("sector");
       if(temp != null){
          sectorId = ( new Integer(temp)).intValue();
      }
            
      //ciiu
      int ciiuId = 1;
      temp = request.getParameter("ciiu");
      if(temp != null){
          ciiuId = ( new Integer(temp)).intValue();
      }
      
      Hashtable sectorList = DataAccess.getSectors();
      Hashtable companyTypes = DataAccess.getCompanyTypes();
      
      
      
      Hashtable ciiuList = DataAccess.getCiiu();
      
      //indices de selección para las listas geográficas
      request.setAttribute("typeId",new Integer(typeId));
      request.setAttribute("sectorId",new Integer(sectorId));
      request.setAttribute("ciiuId",new Integer(ciiuId));
      request.setAttribute("countryId",new Integer(countryId));
      request.setAttribute("cityId",new Integer(cityId));
      request.setAttribute("provinceId", new Integer(provinceId));
      request.setAttribute("neighbourhoodId", new Integer(neighbourhoodId));
      
      
      String socialName = request.getParameter("socialName");
      String commercialName = request.getParameter("commercialName"); 
      String description = request.getParameter("description");
      String companyId = request.getParameter("companyId");
      String sector = request.getParameter("sector");
      String address = request.getParameter("address");
      String phoneNumber1 = request.getParameter("phoneNumber1");
      String phoneNumber2 = request.getParameter("phoneNumber2");
      String contact1 = request.getParameter("contact1");
      String contact2 = request.getParameter("contact2");
      String email = request.getParameter("email");
      String fax = request.getParameter("fax");
      String fenalcoNumber = request.getParameter("fenalcoNumber");
      String login = request.getParameter("login");
      String passwd = request.getParameter("passwd");
      String passwd2 = request.getParameter("passwd2");
      String firstName = request.getParameter("firstName");
      String lastName = request.getParameter("lastName");
      
      String userEmail = request.getParameter("userEmail");
      String idNumber = request.getParameter("idNumber");
      String temp2 = request.getParameter("position");
      if(temp2!= null){
        positionId =  ( new Integer ( temp2 )).intValue();
      }
      
      
      if(type == null){
          type = "";
      }
      if(socialName == null){
          socialName = "";
      }
      if(commercialName == null){
          commercialName = "";
      }
      if(companyId == null){
          companyId = "";
      }
      if(description == null){
          description = "";
      }
      if(sector == null){
          sector = "";
      }
      if(address == null){
          address = "";
      }
      if(phoneNumber1 == null){
          phoneNumber1 = "";
      }
      if(phoneNumber2 == null){
          phoneNumber2 = "";
      }
      if(contact1 == null){
          contact1 = "";
      }
      if(contact2 == null){
          contact2 = "";
      }
      if(email == null){
          email = "";
      }
      if(fax == null){
          fax = "";
      }
      if(fenalcoNumber == null){
          fenalcoNumber = "";
      }
      if(login == null){
          login = "";
      }
      if(passwd == null){
          passwd = "";
      }
      if(passwd2 == null){
          passwd2 = "";
      }
      if(firstName == null){
          firstName = "";
      }
      if(lastName == null){
          lastName = "";
      }
     
      if(userEmail == null){
          userEmail = "";
      }
      if(idNumber == null){
          idNumber = "";
      }
      if(GLN == null){
          GLN = "";
      }
      
      
      //datos empresa
           
      request.setAttribute("type",type);
      request.setAttribute("socialName",socialName);
      request.setAttribute("commercialName",commercialName);
      request.setAttribute("description",description);
      request.setAttribute("companyId",companyId);
      request.setAttribute("sector",sector);
      request.setAttribute("address",address);
      request.setAttribute("phoneNumber1",phoneNumber1);
      request.setAttribute("phoneNumber2",phoneNumber2);
      request.setAttribute("contact1",contact1);
      request.setAttribute("contact2",contact2);
      request.setAttribute("email",email);
      request.setAttribute("fax",fax);
      request.setAttribute("fenalcoNumber",fenalcoNumber);
      //dato usuario
      request.setAttribute("login",login);
      request.setAttribute("passwd",passwd);
      request.setAttribute("passwd2",passwd2);
      request.setAttribute("firstName",firstName);
      request.setAttribute("lastName",lastName);
      request.setAttribute("position",new Integer(positionId));
      
      request.setAttribute("userEmail",userEmail);
      request.setAttribute("idNumber",idNumber);
      request.setAttribute("GLN",GLN);
      //listas
      request.setAttribute("sectorList",sectorList);
      request.setAttribute("companyTypes",companyTypes);
      request.setAttribute("citiesList",citiesList);
      request.setAttribute("countriesList",countriesList);
      request.setAttribute("provincesList",provincesList);
      request.setAttribute("neighbourhoodsList",neighbourhoodsList);
      request.setAttribute("positionList",(new PositionList()).getPositions());
      request.setAttribute("ciiuList",ciiuList);
        
        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
        dispatcher.forward(request, response );
    }
    
    /** Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }
    
    /** Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }
    
    /** Returns a short description of the servlet.
     */
    public String getServletInfo() {
        return "Short description";
    }
    
}
