/*
 * OrdersView.java
 *
 * Created on 10 de agosto de 2004, 17:54
 */

package com.fenalco.servlets.shopkeeper;

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.Store;
import com.fenalco.entities.User;
import com.fenalco.utilities.MessageBuilder;
import com.fenalco.utilities.lists.OrderListViewShopKeeper;

/**
 * Este servlet carga las listas de ordenes de pedido del minorista a través de
 * un objeto <CODE>OrderList</CODE> y presenta la información a través de
 * <CODE>OrderListView</CODE>
 * 
 * @author Mario Linares Vásquez
 */
public class OrdersView extends HttpServlet
{

	/**
	 * Inicializa el servlet.
	 * 
	 * @param config
	 * @throws ServletException
	 */
	public void init( ServletConfig config ) throws ServletException
	{
		super.init(config);

	}

	/**
	 * Destructor de el servlet
	 */
	public void destroy( )
	{

	}

	/**
	 * Procesa las solicitudes de los métodos HTTP <code>GET</code> and
	 * <code>POST</code>. Este método crea una instancia del objeto <CODE>
	 * OrderList</CODE> con el id del usuario y el rol y luego la respectiva
	 * vista como instancia de <CODE>OrderListView</CODE> que será colocada en
	 * el <CODE>reponse</CODE> como atributo con el nombre <CODE>view</CODE>.
	 * Al final se redirecciona el flujo a mispedidos.jsp
	 * 
	 * @param request
	 *            servlet request
	 * @param response
	 *            servlet response
	 */
	protected void processRequest( HttpServletRequest request,
			HttpServletResponse response ) throws ServletException, IOException
	{

		String url = "/minorista/mispedidos.jsp";
		String message = "";
        HttpSession session = request.getSession( false );

	    try
	    {
	        if( session != null && ( User )session.getAttribute( "user" ) != null && ( ( User )session.getAttribute( "user" ) ).getRoleId() == 3 )
			{
				User user = (User) request.getSession().getAttribute("user");
				Store store = (Store) request.getSession().getAttribute("store");
				int storeId = store.getId();
				int companyId = user.getCompanyId();
				String role = user.getRoleName();
	
				// criterios de paginación
				int order = 2;
				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 = 0;
				Date startDate = new Date(0);
				Date endDate = new Date(new java.util.Date().getTime());
				//---------------
				if( request.getParameter("date") != null )
				{
					date = Integer.parseInt(request.getParameter("date"));
				}
	
				if( (request.getParameter("startDate") != null && request
						.getParameter("endDate") != null)
						&& (!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:
							//En pausa
							/*year = new Date(new java.util.Date().getTime())
									.getYear();
							month = new Date(new java.util.Date().getTime())
									.getMonth();
                                                        */
                                                    
                                                        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();
							startDate.setYear(year);
							startDate.setMonth(month);
							startDate.setDate(1);
							endDate.setYear(year);
							endDate.setMonth(month);
							endDate.setDate(31);*/
                                                    
                                                        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(1);
							startDate.setDate(1);
							endDate.setYear(year);
							endDate.setMonth(12);
							startDate.setDate(31);*/
                                                    
                                                        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("order") != null )
				{
					order = Integer.parseInt(request.getParameter("order"));
				}
	
				if( request.getParameter("page") != null )
				{
					page = Integer.parseInt(request.getParameter("page"));
					page = (page < 1) ? 1 : page;
					pageResults = Integer.parseInt(request
							.getParameter("pageResults"));
					//System.out.println("pageResults(antes)-> "+pageResults);
					pageResults = (pageResults < 1) ? 20 : pageResults;
	
				}
	
				//System.out.println("pageResults(despues)-> "+pageResults);
	
				//---------------
	
				//                System.out.println("startDate-->"+startDate+"
				// endDate-->"+endDate);
				OrderList list = new OrderList(companyId, -1, role, startDate,
						endDate, order, false);
	
				//--------------------
	
				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 aux = new Vector();
				for( int i = 0; i < total; i++ )
				{
					if( i >= firstRow && i <= lastRow - 1 )
					{
						aux.addElement(list.getOrders().elementAt(i));
					}
				}
				list.setOrders(aux);
	
				//---------------------
	
				OrderListViewShopKeeper view = new OrderListViewShopKeeper(list,
						storeId);
	
                                
				request.setAttribute("view", view);
				//--------------------------
				request.setAttribute("order", Integer.valueOf(order + ""));
				// información de los criterios de búsqueda
	
				/// 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("startDate") != null && request
						.getParameter("endDate") != 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("date", date + "");
				//--------------------------
	
			}
			else
			{
				message = MessageBuilder.buildMessage(15);
				url = "/index.jsp";
			}
	    }
	    catch( Exception e )
	    {
	        url="/logout";
	        message = MessageBuilder.buildMessage(15);
                e.printStackTrace();
	    }
		request.setAttribute("message", message);
		RequestDispatcher dispatcher = getServletContext()
				.getRequestDispatcher(url);
		dispatcher.forward(request, response);

	}

	/**
	 * Procesa el método HTTP <code>GET</code>.
	 * 
	 * @param request
	 *            servlet request
	 * @param response
	 *            servlet response
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void doGet( HttpServletRequest request,
			HttpServletResponse response ) throws ServletException, IOException
	{
		processRequest(request, response);
	}

	/**
	 * Procesa el método HTTP <code>POST</code> method.
	 * 
	 * @param request
	 *            servlet request
	 * @param response
	 *            servlet response
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void doPost( HttpServletRequest request,
			HttpServletResponse response ) throws ServletException, IOException
	{
		processRequest(request, response);
	}

	/**
	 * Returns a short description of the servlet.
	 * 
	 * @return
	 */
	public String getServletInfo( )
	{
		return "Short description";
	}

}