/*
 * ShopKeepersView.java
 *
 * Created on 10 de agosto de 2004, 18:12
 */

package com.fenalco.servlets.supplier;

import java.io.IOException;

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 java.util.Vector;
import java.sql.Date;
import java.util.Calendar;

import com.fenalco.entities.ShopKeeperList;
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.NonClientShopKeeperListViewSupplier;

/**
 * 
 * @author andres
 * @version
 */
public class ShopKeepersView extends HttpServlet
{

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

	}

	/**
	 * Destroys the servlet.
	 */
	public void destroy( )
	{

	}

	/**
	 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
	 * methods.
	 * 
	 * @param request
	 *            servlet request
	 * @param response
	 *            servlet response
	 */
	protected void processRequest( HttpServletRequest request,
			HttpServletResponse response ) throws ServletException, IOException
	{
		HttpSession session = request.getSession(false);
		RequestDispatcher dispatcher;
		String url;
		String message = "";

	    try
	    {
	        if( session == null || ( User )session.getAttribute( "user" ) == null || ( ( User )session.getAttribute( "user" ) ).getRoleId() != 2 )
			{
				url = "/logout";
				//message = "Sesión no iniciada";
				message = MessageBuilder.buildMessage(15);
			}
			else
			{
                            
                                // criterios de paginación
				int pagina = 1;
				int resultadosPagina = 20;
				int paginas; // numero total de páginas
				int inicio = 0; // numero del primero registro que se va a mostrar
				int fin = 9; // numero del último registro que se va a mostrar
				int total; // numero total de resultados
                                
                                String temp = request.getParameter("page");
                                if( temp == null ){
                                    
                                    pagina = 1;
                                    
                                }else{
                                
                                    pagina = Integer.parseInt( temp );
                                    
                                }
                                
                                pagina = (pagina < 1)? 1 : pagina;
                                temp = request.getParameter( "pageResults" );
                                
                                if( temp == null ){
                                    
                                    resultadosPagina = 20;
                                    
                                }else{
                                
                                    resultadosPagina = Integer.parseInt( temp );
                                    
                                }
                                
                                resultadosPagina = (resultadosPagina < 1)? 20 : resultadosPagina;
                                
                                int countryId = 1; //Se fija en Colombia
                                int provinceId = -1;
                                int cityId = -1;
                                
                                Vector provinces = new Vector();
                                Vector cities = new Vector();
                                String t1 = request.getParameter("province");
                                String t2 = request.getParameter("city");
                                String clicked = request.getParameter("clicked");
                                
                                
                                if( t1 != null && t2 != null && clicked != null ){
                                
                                    provinceId = Integer.parseInt( t1 );
                                    cities = DataAccess.getCities( provinceId );
                                    
                                    if( clicked.equals("0") ){
                                        if( provinceId != -1 ){
                                            cityId = ( (City)cities.elementAt(0) ).getId();
                                        }
                                        
                                    }else{
                                        cityId = Integer.parseInt( t2 );
                                    }
                                    
                                }else{
                                    
                                    provinces = DataAccess.getValidProvinces( countryId );
                                    if( provinces.size() > 0 ){
                                        provinceId = ( ( Province ) provinces.elementAt( 0 ) ).getId();
                                    }
                                    cities = DataAccess.getCities( provinceId );
                                    cityId = ( (City)cities.elementAt(0) ).getId();
                                }
                                
                                System.out.println( "pId: "+ provinceId + " cId: " + cityId );
                                                                
				//Adición de ciudades 
                                provinces = DataAccess.getValidProvinces( countryId );
                                if( provinceId != -1 ){
                                    cities = DataAccess.getCities( provinceId );
                                }
                                
                                
				User supplier = (User) session.getAttribute("user");
				ShopKeeperList shopKeeperList = new ShopKeeperList();
                                
                                int filterNew = 0;
                                
                                int date = 2;
				Date startDate = new Date(0);
				Date endDate = new Date(0);
                                
                                if( request.getParameter("date") != null ){
                                    date = Integer.parseInt( request.getParameter("date") );
                                }
                                
                                int year = 0;
                                int month = 0;
                                switch (date)
                                {
                                        case 1:
                                                startDate = new Date(new java.util.Date()
                                                                .getTime());
                                                endDate = new Date(new java.util.Date()
                                                                .getTime());
                                                break;
                                        case 2:
                                                endDate = new Date(new java.util.Date()
                                                                .getTime());
                                                year = new Date(new java.util.Date().getTime())
                                                                .getYear();
                                                month = new Date(new java.util.Date().getTime())
                                                                .getMonth();
                                                startDate.setYear(year);
                                                startDate.setMonth(month);
                                                startDate.setDate(endDate.getDate() - 7);

                                                break;
                                        case 3:
                                                year = new Date(new java.util.Date().getTime())
                                                                .getYear();
                                                month = new Date(new java.util.Date().getTime())
                                                                .getMonth();
                                                Calendar c = Calendar.getInstance();
                                                startDate.setYear(year);
                                                startDate.setMonth(month);
                                                startDate.setDate(1);

                                                endDate.setYear(year);
                                                endDate.setMonth(month);
                                                c.setTime(startDate);
                                                endDate.setDate(c.getActualMaximum(5));
                                                break;
                                        case 4:
                                                year = new Date(new java.util.Date().getTime())
                                                                .getYear();
                                                startDate.setYear(year);
                                                startDate.setMonth(0);
                                                startDate.setDate(1);
                                                endDate.setYear(year);
                                                endDate.setMonth(11);
                                                endDate.setDate(31);
                                                break;
                                }
                                
                                                              
                                
                                if( request.getParameter("filterNew") != null && !request.getParameter("filterNew").equals("") ){
                                    
                                    filterNew = Integer.parseInt( request.getParameter("filterNew") );
                                    
                                }
                                
                                //Se buscan los minoristas que no son clientes y que están en una ciudad determinada
                                //Se agrega la busqueda de nuevos minoristas entre un rango de fechas
                                String shopKeeperName = request.getParameter("shopKeeperName");
                                if( shopKeeperName == null ){
                                    shopKeeperName="";
                                }
				shopKeeperList.nonClientList(supplier.getCompanyId(), shopKeeperName, startDate, endDate, filterNew  );
                                shopKeeperList.filterByProvince( provinceId );
                                shopKeeperList.filterByCity( cityId );
                                
                                
                                Vector results = new Vector();
                                total = shopKeeperList.getShopKeepers().size();    
                                
                                paginas = (int) Math.ceil((double) total / (double) resultadosPagina);
                                
				if( pagina > paginas ){
					pagina = paginas;
				}
                                
				inicio = (pagina - 1) * resultadosPagina;
				fin = pagina * resultadosPagina;
				inicio = (inicio < 0) ? 0 : inicio;
                                
				if( fin > total ){
					fin = total;
				}
                                
				for( int i = inicio; i < fin; i++ ){
					results.addElement( shopKeeperList.getShopKeepers().elementAt(i) );
                                }
                                
                                shopKeeperList.setShopKeepers( results );
                                
				NonClientShopKeeperListViewSupplier shopKeeperListView = new NonClientShopKeeperListViewSupplier( shopKeeperList );
	
				if( shopKeeperListView == null )
				{
					//Fallo en la creación del listado de minoristas
					//message = "Fallo en la creación del listado de minoristas";
					message = MessageBuilder.buildMessage(9);
					url = "/proveedor/verminoristas.jsp";
				}
				else
				{
					//Todo OK
					//message = "El listado de minoristas se creó correctamente";
					//message = MessageBuilder.buildMessage(3);
					message = "";
					url = "/proveedor/verminoristas.jsp";
	
					request.setAttribute("view", shopKeeperListView);
                                        request.setAttribute("provinces", provinces);
                                        request.setAttribute("provinceId", new Integer(provinceId));
                                        request.setAttribute("cities", cities);
                                        request.setAttribute("cityId", new Integer(cityId));
                                        request.setAttribute("filterNew", new Integer( filterNew ) );
                                        request.setAttribute("date", new Integer( date ) );
				}
                                
                                /// información de la paginacion
                                inicio++; // para no arrancar desde 0
                                inicio = (fin == 0) ? 0 : inicio;
                                request.setAttribute("firstRow", inicio + "");
				request.setAttribute("lastRow", fin + "");
				request.setAttribute("total", total + "");
				request.setAttribute("page", pagina + "");
				request.setAttribute("pages", paginas + "");
				request.setAttribute("pageResults", resultadosPagina + "");
			}
	    }
	    catch( Exception e )
	    {
                e.printStackTrace();
	        url="/logout";
	        message = MessageBuilder.buildMessage(15);
	    }
                
                if( request.getAttribute("message") != null ){
                    message = (String)request.getAttribute("message");
                }
                
		request.setAttribute("message", message);
		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";
	}

}