/*
 * ComparativeSuppliersReport.java
 *
 */

package com.fenalco.servlets.sysmanager.reports;

import java.io.*;
import java.net.*;
import java.sql.Date;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Enumeration;
import java.util.Vector;

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

import com.fenalco.entities.City;
import com.fenalco.entities.Province;
import com.fenalco.entities.DataAccess;

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


import com.fenalco.entities.User;
import com.fenalco.entities.ComparativeReports;
import com.fenalco.utilities.lists.ComparativeReportListViewSysManager;
import com.fenalco.utilities.MessageBuilder;

import co.com.ddt.views.ChartView;
import co.com.ddt.views.ViewBuilder;
import co.com.ddt.chart.ChartBuilder;
import co.com.ddt.views.View;

/**
 *
 * @author  Néstor Romero León
 * @version
 */
public class ComparativeSuppliersReport 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{

                
                ////Combos País - Departamento - Ciudad /////////
                
                Vector countriesList = DataAccess.getCountries();
                Vector provincesList = new Vector();
                Vector citiesList = new Vector();
                
                
                int countryId = 1;
                int provinceId = -1;
                int cityId = -1;
                String combo = "country";
                
                if( request.getParameter("combo") != null ){
                    combo = request.getParameter( "combo" );
                }
                
                System.out.println( "combo: " + combo );
                if( combo.equals("country") ){
                    
                    if( request.getParameter( "country" ) != null ){
                        countryId = Integer.parseInt( request.getParameter( "country" ) );
                    } 
                    
                    provincesList = DataAccess.getProvinces( countryId );
                    
                    citiesList = DataAccess.getCities( provinceId );
                                        
                    
                }else if( combo.equals("province") ){
                
                    countryId = Integer.parseInt( request.getParameter( "country" ) );
                    provinceId = Integer.parseInt( request.getParameter( "province" ) );
                    
                    provincesList = DataAccess.getProvinces( countryId );
                    citiesList = DataAccess.getCities( provinceId );
                    
                    
                }else if( combo.equals("city") ){
                
                    countryId = Integer.parseInt( request.getParameter( "country" ) );
                    provinceId = Integer.parseInt( request.getParameter( "province" ) );
                    cityId = Integer.parseInt( request.getParameter( "city" ) );
                    
                    provincesList = DataAccess.getProvinces( countryId );
                    citiesList = DataAccess.getCities( provinceId );
                    
                }
                
                
                System.out.println( "CountryId: " + countryId );
                System.out.println( "ProvinceId: " + provinceId );
                System.out.println( "CityId: " + cityId );
                
                ////////////////////////////////////////////////////////////////
                
                
                /////////////////////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 = 0;
                if( request.getParameter( "reportType" ) != null ){
                    reportType = Integer.parseInt( request.getParameter("reportType") );
                }
                
                
                ////////////////////////////////////////////////////////////////
                
                ////////////////////////////Generación Reporte//////////////////
                
                ComparativeReports cr = new ComparativeReports();
                cr.comparativeReportsBySupplier( countryId, provinceId, cityId, start, end );  
                
                Vector list = cr.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
                ComparativeReportListViewSysManager view = new ComparativeReportListViewSysManager( list );
                
                //Se construye el gráfico
                String graphic = this.buildGraphic( request, list, reportType );
                
                ////////////////////////////////////////////////////////////////
                

                ///////////////////Envío Parámetros/////////////////////////////
                
                request.setAttribute( "startDate", startDateReturn);
                request.setAttribute( "endDate", endDateReturn);
                request.setAttribute( "date", date + "" );

                request.setAttribute("countryId", new Integer(countryId));
                request.setAttribute("provinceId", new Integer(provinceId));
                request.setAttribute("cityId", new Integer(cityId));
                
                request.setAttribute("countriesList", countriesList);
                request.setAttribute("provincesList", provincesList);
                request.setAttribute("citiesList", citiesList);
                request.setAttribute("combo", combo );
                
                //request.setAttribute("sort", new Integer( sort ) );
                
                request.setAttribute("view", view);
                
                request.setAttribute( "headers", this.buildHeaders( ) );

                request.setAttribute("graphic",graphic ); 
                
                /// 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/comparativo_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( ){
        
        Vector headers = new Vector();
        
        headers.add( "Proveedor" );
        headers.add( "Pedidos" );
        headers.add( "Total<br>Ventas" );
        headers.add( "Pedidos %" );
        headers.add( "Total %");
        
        return headers;
        
    }
    
    public String buildGraphic( HttpServletRequest request, Vector report, int reportType ){
        
            String title = "Comparativo Proveedores";
            
            //No se requieren para este gráfico
            Vector header = new Vector();
            //header.addElement( "" );
            
            Vector data = new Vector();
            Vector labels = new Vector();
            
            if( reportType == 0 ){
                title += " - Pedidos " ;
                header.addElement( "Pedidos" );
            }else{
                title += " - Compras ";
                header.addElement( "Compras" );
            }
            
            Vector dataRow = new Vector();
            
            
            for( int i=0;i<report.size();i++ ){
                
                Vector row = new Vector();
                row = (Vector)report.elementAt( i );
                
                labels.addElement( row.elementAt( 0 ) );
                
                dataRow = new Vector();
                
                if( reportType == 0 ){
                    double q = ((Integer)row.elementAt( 1 )).doubleValue();
                    dataRow.addElement( new Double( q ) );
                }else{
                    dataRow.addElement( row.elementAt( 2 ) );
                }
                
                data.addElement( dataRow );
                
            }
            
            ChartView chartView = (ChartView)ViewBuilder.buildView( View.BAR_CHART, title, header, labels, data, request );
            return chartView.getChartImg();
        
    }
    
    /** 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";
    }
    
}
