/*
 * OrderListView.java
 *
 * Created on 17 de septiembre de 2004, 15:28
 */

package com.fenalco.servlets.sysmanager;

import java.io.IOException;
import java.sql.Date;
import java.util.Calendar;
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.OrderList;
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.OrderListViewSysManager;
import com.fenalco.utilities.lists.ShopKeeperListViewSysManager;
import com.fenalco.utilities.lists.SupplierListViewSysManager;

/**
 * 
 * @author Juan Ernesto Peña Kaltekis
 * @version
 */
public class OrderListView 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>.
	 * 
	 * -Se cargan una lista de proveedores y una de minoristas -Se crea un
	 * objeto de tipo <CODE>OrderList</CODE> con losparámetdro de búsqueda que
	 * vivnen en el request. -Se crea un objeto de tipo <CODE>
	 * OrderListViewSysManger</CODE> con el objeto anterior y se envía en el
	 * request
	 * 
	 * -Redirecciona a listapedidos.jsp
	 * 
	 * @param request
	 *            petición al servlet
	 * @param response
	 *            respuesta del servlet
	 */
	protected void processRequest( HttpServletRequest request,
			HttpServletResponse response ) throws ServletException, IOException
	{

		HttpSession session = request.getSession(false);
		String url = "";
		String message = "";

	    try
	    {
	        if( session == null || ( User )session.getAttribute( "user" ) == null || ( ( User )session.getAttribute( "user" ) ).getRoleId() != 1 )
			{
				url = "/index.jsp";
				message = MessageBuilder.buildMessage(15);
			}
			else
			{
				SupplierList suppliers = new SupplierList();
				SupplierListViewSysManager suppliersView = new SupplierListViewSysManager(
						suppliers);
				ShopKeeperList shopKeepers = new ShopKeeperList();
				ShopKeeperListViewSysManager shopKeepersView = new ShopKeeperListViewSysManager(
						shopKeepers);
	
				// captura los criterios de búsqueda provenientes del jsp
				int company = 0;
				int order = 2;
				String role = "";
				int companyType = 3;
				int supplier = 0;
				int shopKeeper = 0;
				boolean historical = false;
	
				// 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
	
				int date = 1;
				Date startDate = new Date(0);
				Date endDate = new Date(0);
	
				OrderList list = null;
				OrderListViewSysManager view = null;
	
				//verifica si es la primera vez
				if( request.getParameter("companyType") != null )
				{
					//if(true){
					try
					{
	
						if( request.getParameterValues("historical") != null )
						{
							historical = true;
						}
	
						supplier = Integer.parseInt(request
								.getParameter("supplier"));
						/*
						 * String aux[]=request.getParameterValues("supplier");
						 * supplier=Integer.parseInt(aux[0]);
						 */
						shopKeeper = Integer.parseInt(request
								.getParameter("shopKeeper"));
						/*
						 * aux=request.getParameterValues("shopKeeper");
						 * shopKeeper=Integer.parseInt(aux[0]);
						 */
						date = Integer.parseInt(request.getParameter("date"));
	
						//companyType -> 1:minorista, 2:proveedor
						companyType = Integer.parseInt(request
								.getParameter("companyType"));
						role = "";
						if( companyType == 1 )
						{
							company = Integer.parseInt(request
									.getParameter("shopKeeper"));
							role = "Minorista";
						}
						else
							if( companyType == 2 )
							{
								company = Integer.parseInt(request
										.getParameter("supplier"));
								role = "Proveedor";
							}
							else
							{
								role = "Administrador";
							}
	
						if( !request.getParameter("startDate").equals("")
								&& !request.getParameter("endDate").equals("") )
						{
							startDate = Date.valueOf(request
									.getParameter("startDate"));
							endDate = Date.valueOf(request.getParameter("endDate"));
						}
						else
						{
							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;
							}
						}
	
						//order = Integer.parseInt( request.getParameter( "order" )
						// );
	
						page = Integer.parseInt(request.getParameter("page"));
						page = (page < 1) ? 1 : page;
						pageResults = Integer.parseInt(request
								.getParameter("pageResults"));
						pageResults = (pageResults < 1) ? 20 : pageResults;
					}
					catch (Exception e)
					{
						System.out
								.println("Excepcion en el servlet de pedidos --> "
										+ e);
					}
	
					list = new OrderList(company, -1, role, startDate, endDate,
							order, historical);
	
					// aqui se efectua la paginación
					total = list.getOrders().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 tempOrders = new Vector();
					for( int i = 0; i < total; i++ )
					{
						if( i >= firstRow && i <= lastRow - 1 )
						{
							tempOrders.addElement(list.getOrders().elementAt(i));
						}
					}
	
					list.setOrders(tempOrders);
					view = new OrderListViewSysManager(list);
				}
				else
				{
					list = new OrderList(company, -1, role, startDate, endDate,
							order, historical);
					view = new OrderListViewSysManager(list);
				}
	
				request.setAttribute("suppliers", suppliersView);
				request.setAttribute("shopKeepers", shopKeepersView);
				request.setAttribute("view", view);
	
				// información de los criterios de búsqueda
				request.setAttribute("supplier", Integer.valueOf(supplier + ""));
				request
						.setAttribute("shopKeeper", Integer
								.valueOf(shopKeeper + ""));
				request.setAttribute("order", Integer.valueOf(order + ""));
				request.setAttribute("historical", Boolean.toString(historical));
	
				/// 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 + "");
	
				if( request.getParameter("companyType") != null
						&& !request.getParameter("startDate").equals("")
						&& !request.getParameter("endDate").equals("") )
				{
					startDate.setYear(startDate.getYear());
					endDate.setYear(endDate.getYear());
					request.setAttribute("startDate", startDate.toString());
					request.setAttribute("endDate", endDate.toString());
				}
				else
				{
					request.setAttribute("startDate", "");
					request.setAttribute("endDate", "");
				}
				request.setAttribute("companyType", companyType + "");
				request.setAttribute("date", date + "");
	
				url = "/administrador/listapedidos.jsp";
			}
	    }
	    catch( Exception e )
	    {
	        url="/logout";
	        message = MessageBuilder.buildMessage(15);
	    }

		request.setAttribute("message", message);
		RequestDispatcher rd = getServletContext().getRequestDispatcher(url);
		rd.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";
	}

}