/*
 * SupplierReports.java
 *
 */

package com.fenalco.servlets.sysmanager.reports;

import java.io.*;
import java.net.*;

import javax.servlet.*;
import javax.servlet.http.*;

import com.fenalco.entities.SupplierList;
import com.fenalco.entities.Supplier;

import java.util.GregorianCalendar;
import java.util.Calendar;
import java.util.Vector;
import java.sql.Date;

import com.fenalco.entities.User;
import com.fenalco.entities.ReportDataAccess;
import com.fenalco.utilities.lists.SupplierListViewSysManager;
import com.fenalco.utilities.lists.ReportSupplierListViewSysManager;

import com.fenalco.utilities.MessageBuilder;

/**
 *
 * @author  Néstor Romero León
 * @version
 */
public class SupplierReports 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 {
        
        String url = "";
        String message = "";
        HttpSession session = request.getSession(false);
        //try{
            if( session == null || ( User )session.getAttribute( "user" ) == null || ( ( User )session.getAttribute( "user" ) ).getRoleId() != 5 ){
                url = "/index.jsp";
                message = MessageBuilder.buildMessage(15);
            }else{

                //////////////////////Combo Proveedor///////////////////////////
                SupplierList suppliers = new SupplierList();
                int supplierId = -1;
                if( suppliers.getSuppliers().size() > 0 ){
                    supplierId = ((Supplier)suppliers.getSuppliers().elementAt(0)).getSupplierId();
                }
                
                if( request.getParameter("supplier") != null  ){
                    supplierId = Integer.parseInt( request.getParameter( "supplier" ) );
                }
                
                SupplierListViewSysManager suppliersView = new SupplierListViewSysManager( suppliers );
                
                System.out.println( "SupId: " + supplierId );
                ////////////////////////////////////////////////////////////////
                
                
                /////////////////////Construcción de Fechas/////////////////////
                
                int date = 1;
                GregorianCalendar calendar = new GregorianCalendar();
                Date start = new Date( calendar.getTimeInMillis() );
                Date end = new Date( calendar.getTimeInMillis() );
                String startDateReturn = "";
                String endDateReturn = "";
                
                
                //Se seleccionó un acceso rápido
                if( (request.getParameter("startDate")== null  || 
                    request.getParameter("startDate").equals("") ) ||
                    (request.getParameter("endDate")== null || 
                    request.getParameter("endDate").equals("") )
                    ){
                        
                    if( request.getParameter( "date" ) != null ){
                        date = Integer.parseInt( request.getParameter( "date" ) );
                    }
                    
                    java.util.Date aux = new java.util.Date();
                    
                    switch( date ){
                        //Hoy
                        case 1:
                            //Nothing to do here!!
                        break;
                        
                        //Últimos 8 días
                        case 2:
                            
                            calendar.set( calendar.DAY_OF_MONTH, calendar.get( Calendar.DATE) - 7 );
                            start.setTime( calendar.getTimeInMillis() );
                            
                        break;
                        
                        //Este Mes
                        case 3:
                            
                            calendar.set( calendar.DAY_OF_MONTH, 1 );
                            start.setTime( calendar.getTimeInMillis() );

                            calendar.set( calendar.MONTH, calendar.get( calendar.MONTH ) + 1 );
                            calendar.set( calendar.DAY_OF_MONTH, 1 );
                            end.setTime( calendar.getTimeInMillis() );
                            
                        break;
                        
                        //Este año
                        case 4:
                            
                            calendar.set( calendar.DAY_OF_YEAR, 1);
                            start.setTime( calendar.getTimeInMillis() );

                            calendar.set( calendar.YEAR, calendar.get( calendar.YEAR ) + 1 );
                            calendar.set( calendar.DAY_OF_YEAR, 1);
                            end.setTime( calendar.getTimeInMillis() );
                            
                        break;
                    }
                
                }else{
                    
                    //Los campos de fechas contienen datos
                    
                    String aux = request.getParameter( "startDate" );
                    Date auxDate = Date.valueOf( aux );
                    start = new Date( auxDate.getTime() );
                    
                    aux = request.getParameter( "endDate" );
                    auxDate = Date.valueOf( aux );
                    end = new Date( auxDate.getTime() );
                    
                    startDateReturn = start.toString();
                    endDateReturn = end.toString();
                    
                }
                
                //Se asignan las fechas
                
                System.out.println( start );
                System.out.println( end );
                ////////////////////////////////////////////////////////////////

                ///////////////////////////////Paginación///////////////////////
                //Criterios de Paginación
                int page = 0;
                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 = 0; // numero del último registro que se va a mostrar
                int total = 0; // numero total de resultados
                
                
                if(request.getParameter("page")!=null){
                    try{
                        page = Integer.parseInt(request.getParameter("page"));
                    }catch(NumberFormatException nfe){
                        page = 1;
                    }
                    page = (page < 1) ? 1 : page;
                    try{
                        pageResults = Integer.parseInt(request.getParameter("pageResults"));
                    }catch(NumberFormatException nfe){
                        pageResults = 20;
                    }
                    pageResults = (pageResults < 1) ? 20 : pageResults;
                }
                
                ////////////////////////////////////////////////////////////////
                
                /////////////////////////////Parámetro de Ordenamiento//////////
                int reportType = 1;
                if( request.getParameter( "reportType" ) != null ){
                    reportType = Integer.parseInt( request.getParameter("reportType") );
                }
                
                
                ////////////////////////////////////////////////////////////////
                
                
                ////////////////////////////Generación Reporte//////////////////
                
                ReportDataAccess rda = new ReportDataAccess();
                rda.supplierReportBuilder( supplierId, start, end, reportType );
                
                Vector list = rda.getReport();
                total = list.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 temp = new Vector();
                for( int i = 0; i < total; i++ ){
                    if( i >= firstRow && i <= lastRow - 1 ){
                        temp.addElement(list.elementAt(i));
                    } 
                }

                list = temp ;
                
                //Se construye la vista
                ReportSupplierListViewSysManager view = new ReportSupplierListViewSysManager( list, reportType );
                
                
                ///////////////////Envío Parámetros/////////////////////////////
                
                request.setAttribute( "startDate", startDateReturn);
                request.setAttribute( "endDate", endDateReturn);
                request.setAttribute( "date", date + "" );

                request.setAttribute( "view", view);
                
                request.setAttribute( "suppliers", suppliersView );
                request.setAttribute( "supplier", new Integer(supplierId) );
                
                request.setAttribute( "reportType", new Integer(reportType) );
                
                request.setAttribute( "headers", this.buildHeaders( reportType ) );

                
                /// 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 + "");
                
                url = "/administrador/reportes/proveedores.jsp";
                
                ////////////////////////////////////////////////////////////////
                
            }    
        /*}catch( Exception e ){
            System.out.println(e);
            url="/logout";
            message = MessageBuilder.buildMessage(15);
        }*/

        //System.out.println( "Sale de Orders Report" );
        
        request.setAttribute("message", message);
        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
        dispatcher.forward(request, response);
        
    }
    
    public Vector buildHeaders( int reportType ){
        
        Vector headers = new Vector();
        //headers.add( "Id" );
        if( reportType == 1 ){
            
            //headers.add( "Id" );
            headers.add( "Descripción" );
            headers.add( "Fecha Inicio" );
            headers.add( "Fecha Fin" );
        
            headers.add( "Unidades<br>Transadas" );
            headers.add( "Total<br>Ventas" );
            headers.add( "Unidades %" );
            headers.add( "Total %");
            
        }else{
            
            headers.add( "Id" );
            headers.add( "Categoría" );
            headers.add( "Productos Activos" );
            headers.add( "Producto %" );
        }
        
        
        return headers;
        
    }
    
    /** 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";
    }
    
}
