/*
 * OrdersReport.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.Neighbourhood;
import com.fenalco.entities.Zone;
import com.fenalco.entities.City;
import com.fenalco.entities.Province;
import com.fenalco.entities.DataAccess;

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

import com.fenalco.entities.ShopKeeperList;
import com.fenalco.entities.StoreList;
import com.fenalco.entities.ShopKeeper;
import com.fenalco.entities.Store;

import com.fenalco.entities.CategoryList;

import com.fenalco.entities.User;
import com.fenalco.entities.OrderList;
import com.fenalco.entities.GeneralReports;
import com.fenalco.utilities.lists.SupplierListViewSysManager;
import com.fenalco.utilities.lists.CommunityListView;
import com.fenalco.utilities.lists.ShopKeeperListViewSysManager;
import com.fenalco.utilities.lists.StoreListViewSupplier;
import com.fenalco.utilities.lists.ReportOrderListViewSysManager;

import com.fenalco.utilities.MessageBuilder;

/**
 *
 * @author  Néstor Romero
 * @version
 */
public class OrdersReport 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 );
                ////////////////////////////////////////////////////////////////
                
                /////////////////////Combo Comunidad////////////////////////////
                CommunityList communities = new CommunityList( supplierId );
                int communityId = -1;
                if( communities.getCommunities().size() > 0 ){
                    communityId = ((Community)communities.getCommunities().elementAt(0)).getId();
                }
                
                if( request.getParameter("community") != null  ){
                    communityId = Integer.parseInt( request.getParameter( "community" ) );
                }
                
                CommunityListView communitiesView = new CommunityListView( communities );
                
                
                
                ////////////////////////////////////////////////////////////////

                //////////////////////Combo Minorista///////////////////////////
                ShopKeeperList shopKeepers = new ShopKeeperList();
                int shopKeeperId = -1;
                if( shopKeepers.getShopKeepers().size() > 0 ){
                    shopKeeperId = ((ShopKeeper)shopKeepers.getShopKeepers().elementAt(0)).getShopKeeperId();
                }
                
                if( request.getParameter("shopkeeper") != null ){
                    shopKeeperId = Integer.parseInt( request.getParameter("shopkeeper") );
                } 
                
                ShopKeeperListViewSysManager shopKeepersView = new ShopKeeperListViewSysManager( shopKeepers );
                
                
                System.out.println( "ShopId: " + shopKeeperId );
                ////////////////////////////////////////////////////////////////
                
                ////////////////////Combo Establecimiento///////////////////////
                StoreList stores = new StoreList( shopKeeperId );
                int storeId = -1;
                if( stores.getStores().size() > 0 ){
                    storeId = ((Store)stores.getStores().elementAt(0)).getId();
                }
                
                if( request.getParameter("store") != null ){
                    storeId = Integer.parseInt( request.getParameter("store") );
                }
                
                StoreListViewSupplier storesView = new StoreListViewSupplier( stores );
                
                
                System.out.println( "StoreId: " + storeId );
                
                ////////////////////////////////////////////////////////////////
                
                
                ////////////////////////Tipo Empresa////////////////////////////
                int companyType = 1;
                if( request.getParameter( "companyType" ) != null ){
                    companyType = Integer.parseInt( request.getParameter( "companyType" ) );
                }
                ////////////////////////////////////////////////////////////////
                
                ////////////////////Categorías Productos////////////////////////
                
                CategoryList categories = new CategoryList();
                int categoryId = -1;
                
                if( request.getParameter("category") != null ){
                    categoryId = Integer.parseInt( request.getParameter("category") );
                }
                
                ////////////////////////////////////////////////////////////////
                
                ////Combos País - Departamento - Ciudad - Zona - Barrio/////////
                
                Vector countriesList = DataAccess.getCountries();
                Vector provincesList = new Vector();
                Vector citiesList = new Vector();
                Vector zonesList = new Vector();
                Vector neighbourhoodsList = new Vector();
                
                int countryId = 1;
                int provinceId = -1;
                int cityId = -1;
                int zoneId = -1;
                int neighbourhoodId = -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 );
                    /*
                    if( provincesList.size() > 0 ){
                        provinceId = ((Province)provincesList.elementAt(0)).getId();
                    }
                     */
                    
                    citiesList = DataAccess.getCities( provinceId );
                    /*
                    if( citiesList.size() > 0 ){
                        cityId = ((City)citiesList.elementAt(0)).getId();
                    }
                     */
                                        
                    zonesList = DataAccess.getZones( cityId );
                    /*
                    if( zonesList.size() > 0 ){
                        zoneId = ((Zone)zonesList.elementAt(0)).getId();
                    }
                     */
                    
                    neighbourhoodsList = DataAccess.getNeighbourhoodsZone( zoneId );
                    /*
                    if( neighbourhoodsList.size() > 0 ){
                        neighbourhoodId = ((Neighbourhood)neighbourhoodsList.elementAt(0)).getId();
                    }
                     */
                    
                }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 );
                    /*
                    if( citiesList.size() > 0 ){
                        cityId = ((City)citiesList.elementAt(0)).getId();
                    }
                     */
                                        
                    zonesList = DataAccess.getZones( cityId );
                    /*
                    if( zonesList.size() > 0 ){
                        zoneId = ((Zone)zonesList.elementAt(0)).getId();
                    }
                     */
                    
                    neighbourhoodsList = DataAccess.getNeighbourhoodsZone( zoneId );
                    /*
                    if( neighbourhoodsList.size() > 0 ){
                        neighbourhoodId = ((Neighbourhood)neighbourhoodsList.elementAt(0)).getId();
                    }
                     */
                    
                }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 );
                    zonesList = DataAccess.getZones( cityId );
                    /*
                    if( zonesList.size() > 0 ){
                        zoneId = ((Zone)zonesList.elementAt(0)).getId();
                    }
                     */
                    
                    neighbourhoodsList = DataAccess.getNeighbourhoodsZone( zoneId );
                    /*
                    if( neighbourhoodsList.size() > 0 ){
                        neighbourhoodId = ((Neighbourhood)neighbourhoodsList.elementAt(0)).getId();
                    }
                     */
                    
                    
                }else if( combo.equals("zone") ){
                
                    countryId = Integer.parseInt( request.getParameter( "country" ) );
                    provinceId = Integer.parseInt( request.getParameter( "province" ) );
                    cityId = Integer.parseInt( request.getParameter( "city" ) );
                    zoneId = Integer.parseInt( request.getParameter( "zone" ) );
                    
                    provincesList = DataAccess.getProvinces( countryId );
                    citiesList = DataAccess.getCities( provinceId );
                    zonesList = DataAccess.getZones( cityId );
                    neighbourhoodsList = DataAccess.getNeighbourhoodsZone( zoneId );
                    /*
                    if( neighbourhoodsList.size() > 0 ){
                        neighbourhoodId = ((Neighbourhood)neighbourhoodsList.elementAt(0)).getId();
                    }
                     */
                    
                }
                
                
                System.out.println( "CountryId: " + countryId );
                System.out.println( "ProvinceId: " + provinceId );
                System.out.println( "CityId: " + cityId );
                System.out.println( "ZoneId: " + zoneId );
                System.out.println( "NeighbourhoodId: " + neighbourhoodId );
                
                
                ////////////////////////////////////////////////////////////////
                
                
                /////////////////////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 );
                ////////////////////////////////////////////////////////////////

                ///////////////////////////////Superofertas/////////////////////
                
                int superOffer = 0;
                if( request.getParameter("superOffer") != null ){
                    superOffer = Integer.parseInt( request.getParameter("superOffer") );
                }
                
                ////////////////////////////////////////////////////////////////
                
                /////////////////////////////Forma de compra////////////////////
                int shoppingMethod = -1;
                if( request.getParameter("shoppingMethod") != null ){
                    shoppingMethod = Integer.parseInt( request.getParameter("shoppingMethod") );
                }
                
                ///////////////////////////////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;
                }
                
                
                
                ////////////////////////////////////////////////////////////////
                
                
                ////////////////////////////Generación Reporte//////////////////
                int companyId = (companyType==1)?shopKeeperId:supplierId;
                
                System.out.println( "Company Id: " + companyId  + " :: " + companyType );
                
                GeneralReports reports = new GeneralReports();
                Vector list = reports.reportBuilder( companyType, companyId, storeId, start, end, countryId, provinceId, 
                                                            cityId, zoneId, neighbourhoodId, superOffer, categoryId, shoppingMethod );
                
                Vector stats = reports.getStats( categoryId );
                
                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 ;
                
                //Creación Vista !!!! TODO
                boolean hasCategory = (categoryId != -1 )?true:false;
                boolean hasStore = (storeId != -1 )?true:false;
                ReportOrderListViewSysManager view = new ReportOrderListViewSysManager( list, companyType, categoryId, hasStore );
                
                ////////////////////////////////////////////////////////////////
                

                ///////////////////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("zoneId", new Integer(zoneId));
                request.setAttribute("neighbourhoodId", new Integer( neighbourhoodId ) );

                request.setAttribute("countriesList", countriesList);
                request.setAttribute("provincesList", provincesList);
                request.setAttribute("citiesList", citiesList);
                request.setAttribute("zonesList", zonesList );
                request.setAttribute("neighbourhoodsList", neighbourhoodsList );
                request.setAttribute("combo", combo );
                
                request.setAttribute("superOffer", new Integer(superOffer) );
                request.setAttribute("shoppingMethod", new Integer(shoppingMethod) );
                
                request.setAttribute("view", view);
                request.setAttribute( "stats", stats ); 
                
                request.setAttribute( "suppliers", suppliersView );
                request.setAttribute( "supplier", new Integer(supplierId) );
                request.setAttribute( "communities", communitiesView );
                request.setAttribute( "community", new Integer( communityId ) );
                
                request.setAttribute( "shopkeepers", shopKeepersView );
                request.setAttribute( "shopkeeper", new Integer( shopKeeperId ) ); 
                request.setAttribute( "stores", storesView );
                request.setAttribute( "store", new Integer( storeId ) );
                
                request.setAttribute( "categories", categories );
                request.setAttribute( "categoryId", new Integer( categoryId ) );
                
                request.setAttribute( "companyType", new Integer( companyType ) );
                
                request.setAttribute( "headers", this.buildHeaders( companyType, categoryId, hasStore ) );

                /// 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/pedidos.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 companyType, int categoryId, boolean hasStore ){
        
        Vector headers = new Vector();
        headers.add( "Id Pedido" );
        if( companyType == 1 ){
            headers.add( "Minorista" );
        }else{
            headers.add( "Proveedor" );
        }
        
        if( hasStore ){
            headers.add( "Establecimiento" );
        }
        
        if( categoryId != -1 ){
            headers.add( "Categoría" );
        }
        
        headers.add( "Ciudad" );
        headers.add( "Fecha" );
        headers.add( "Hora" );
        headers.add( "Valor<br>Total" );
        //headers.add( "Valor<br>sin<br>Descuento" );
        
        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";
    }
    
}
