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

package com.fenalco.servlets.supplier;

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.Order;
import com.fenalco.entities.DataAccess;
import com.fenalco.entities.User;
import com.fenalco.utilities.MessageBuilder;
import com.fenalco.utilities.lists.OrderListViewSupplier;
/**
 *
 * @author  Juan Ernesto Peña Kaltekis
 * @version
 */
public class OrdersView 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);
        String url = "";
        String message = "";

	    try
	    {
	        if( session == null || ( User )session.getAttribute( "user" ) == null || ( ( User )session.getAttribute( "user" ) ).getRoleId() != 2 )
	        {
	            url="/logout";
	            message = MessageBuilder.buildMessage(15);
	        }
	        else
	        {
	            User supplier = (User)session.getAttribute("user");
	            
	            // captura los criterios de búsqueda provenientes del jsp
	            int company = 0;
	            int order = 2;
	            String role="";
	           
	
	            // 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=4;
	            Date startDate=new Date(0);
	            Date endDate= new Date(0);
	            
	            OrderList list=null;
	            OrderListViewSupplier view=null;
	            
                    //Se genera la sumatoria de los resultados mostrados
                        double sumTotal = 0;
                        Order auxOrder = new Order();
                        
                        
	            //verifica si es la primera vez            
	            //if(request.getParameter("companyType")!=null){            
	            if(true){                            
	            
	                try
	                {   
	                        /*
	                        System.out.println("date-> "+request.getParameter("date"));
	                        System.out.println("startDate-> "+request.getParameter("startDate"));
	                        System.out.println("endDate-> "+request.getParameter("endDate"));
	                        System.out.println("page-> "+request.getParameter("page"));
	                        System.out.println("pageResults-> "+request.getParameter("pageResults"));
	                        */
	                        
	                        company = supplier.getCompanyId();
	                        role="Proveedor";
	                        
	                        if(request.getParameter("date")!=null){
	                            date = Integer.parseInt(request.getParameter("date"));
	                        }
	                        
	                        
	                         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" ) );
	                        //System.out.println("pageResults(antes)-> "+pageResults);
	                        pageResults = ( pageResults < 1 ) ? 20 : pageResults;
	                        //System.out.println("pageResults(despues)-> "+pageResults);
	
	                }
	                catch( Exception e )
	                {
	                    //System.out.println( "Excepcion en el servlet de pedidos --> " + e );
	                    //e.printStackTrace();
	                }
	
	
	                // hago la búsqueda y obtengo solo los ids de los productos que cumplen
	                // los criterios seleccionados
	                System.out.println("Order " + order);
	                list = new OrderList(company,-1,role,startDate,endDate,order,false);
	
	                //Vector ids = lista.loadIds( esNombre, nombre, proveedor, categoria, orden, proveedores );
	
	                // aqui se efectua la paginación
	                total = list.getOrders().size();
                        System.out.println( "Size: " + total );
	                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;
	                }
	
	                int length = list.getOrders().size();
	                Vector auxResult = new Vector();
                        
                        
                        
	                for(int i=0;i<length;i++){
	                    if(i>=firstRow && i<=lastRow-1){
                                auxOrder = (Order)list.getOrders().elementAt(i);
                                sumTotal += auxOrder.getValue();
	                        auxResult.addElement(list.getOrders().elementAt(i));
	                    }
	                }
	                
	                list.setOrders(auxResult);
	                view = new OrderListViewSupplier(list);
	            }else{
	                
	            }
	            
	            //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 + "" ) );
	            
	            /// 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 + "" );
                    
                    request.setAttribute( "sumTotal", DataAccess.getCurrency( sumTotal ) ); 
	            url = "/proveedor/ordenescompra.jsp"; 
	        }
	        
	        if(request.getAttribute("message")!=null){
	            message = (String)request.getAttribute("message");
	        }
	    }
	    catch( Exception e )
	    {
	        url="/logout";
	        message = MessageBuilder.buildMessage(15);
	    }

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