/*
 * LoadOrderReportData.java
 *
 * Created on 10 de octubre de 2004, 01:09 PM
 */

package com.fenalco.servlets.sysmanager;

import java.io.IOException;
import java.sql.Date;
import java.util.Calendar;
import java.util.Vector;
import java.util.Enumeration;

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.ReportOrderList;
import com.fenalco.entities.OrderList;
import com.fenalco.entities.ShopKeeperList;
import com.fenalco.entities.SupplierList;
import com.fenalco.entities.CommunityList;
import com.fenalco.entities.StoreList;
import com.fenalco.utilities.MessageBuilder;
import com.fenalco.utilities.lists.OrderListViewSysManager;
import com.fenalco.utilities.lists.ShopKeeperListViewSysManager;
import com.fenalco.utilities.lists.SupplierListViewSysManager;
import com.fenalco.utilities.lists.CommunityListView;
import com.fenalco.utilities.lists.StoreListViewSupplier;
import com.fenalco.utilities.lists.StoreListViewShopKeeper;

import com.fenalco.entities.Supplier;
import com.fenalco.entities.ShopKeeper;
import com.fenalco.entities.Community;
import com.fenalco.entities.Store;

/**
 *
 * @author  Sager
 * @version
 */
public class LoadOrderReportData 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 = "";

        if(session == null){
            url="/index.jsp";
            message = MessageBuilder.buildMessage(15);
        }else{
            SupplierList suppliers = new SupplierList();
            SupplierListViewSysManager suppliersView = new SupplierListViewSysManager( suppliers );
            ShopKeeperList shopKeepers = new ShopKeeperList();
            ShopKeeperListViewSysManager shopKeepersView = new ShopKeeperListViewSysManager(shopKeepers);
            CommunityList communities = null;            
            CommunityListView communitiesView = null;
            StoreList storesSupplier = null;
            StoreListViewSupplier storesSupplierView = null;
            StoreList storesShopKeeper = null;
            StoreListViewShopKeeper storesShopKeeperView = null;
            
            
            
            // captura los criterios de búsqueda provenientes del jsp
            int company = -1;
            int order = 2;
            int companyType = -1;
            int supplier=-1;
            int shopKeeper=-1;
            int community=-1;
            int storeSupplier=-1;
            int storeShopKeeper=-1;
            int superOffer=0;
            int transactionType = 1;
            
            String orderCriteria="";
            
            boolean historical=false;

            // 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=1;
            Date startDate=new Date(0);
            Date endDate= new Date(0);
            
            OrderList list=null;
            OrderListViewSysManager view=null;
            ReportOrderList reportList=null;

            
            int supplierSql=-1;
            int shopKeeperSql=-1;
            int communitySql=-1;
            int storeSupplierSql=-1;
            int storeShopKeeperSql=-1;
            
            String combo = request.getParameter("combo");
            
            //verifica si es la primera vez            
            if(combo!=null){            
            //if(true){                            
                try{   
                    
                        if(request.getParameter("transactionType")!=null){
                            transactionType=Integer.parseInt(request.getParameter("transactionType"));
                            System.out.println("transactionType->"+Integer.parseInt(request.getParameter("transactionType")));
                        }
                        
                        if(request.getParameter("superOffer")!=null){
                            superOffer=Integer.parseInt(request.getParameter("superOffer"));
                            System.out.println("superOffer->"+Integer.parseInt(request.getParameter("superOffer")));
                        }
                        
                        //Proveedor
                        if(request.getParameter("supplier")!=null){
                            supplier=Integer.parseInt(request.getParameter("supplier"));                        
                            System.out.println("supplier->"+Integer.parseInt(request.getParameter("supplier")));
                        }    
                        if(request.getParameter("community")!=null){
                            community=Integer.parseInt(request.getParameter("community"));
                            System.out.println("community->"+Integer.parseInt(request.getParameter("community")));
                        }
                        if(request.getParameter("storeSupplier")!=null){
                            storeSupplier=Integer.parseInt(request.getParameter("storeSupplier"));
                            System.out.println("storeSupplier->"+Integer.parseInt(request.getParameter("storeSupplier")));
                        }

                        //Minorista
                        if(request.getParameter("shopKeeper")!=null){
                            shopKeeper=Integer.parseInt(request.getParameter("shopKeeper"));
                            System.out.println("shopKeeper->"+Integer.parseInt(request.getParameter("shopKeeper")));
                        }
                        if(request.getParameter("storeShopKeeper")!=null){
                            storeShopKeeper=Integer.parseInt(request.getParameter("storeShopKeeper"));
                            System.out.println("storeShopKeeper->"+Integer.parseInt(request.getParameter("storeShopKeeper")));
                        }
                        
                        
			
                        if(combo.equals("supplier")){
                            communities = new CommunityList(supplier);
                            communitiesView = new CommunityListView(communities);
                            Enumeration e = communities.getCommunities().elements();
                            if(e.hasMoreElements()){
                                community = ((Community)e.nextElement()).getId();
                                storesSupplier = new StoreList();
                                storesSupplier.getCommunityStores(-1, community);
                                storesSupplierView = new StoreListViewSupplier(storesSupplier);
                                e = storesSupplier.getStores().elements();
                                if(e.hasMoreElements()){
                                    storeSupplier = ((Store)e.nextElement()).getId();
                                }
                            }
                            
                            //Minorista
                            storesShopKeeper = new StoreList(shopKeeper);
                            storesShopKeeperView = new StoreListViewShopKeeper(storesShopKeeper);
                            e = storesShopKeeper.getStores().elements();
                            if(e.hasMoreElements()){
                                storeShopKeeper = ((Store)e.nextElement()).getId();
                            }  
                            
                            
                        }else if(combo.equals("community")){
                            storesSupplier = new StoreList();
                            storesSupplier.getCommunityStores(-1, community);
                            storesSupplierView = new StoreListViewSupplier(storesSupplier);
                            Enumeration e = storesSupplier.getStores().elements();
                            if(e.hasMoreElements()){
                                storeSupplier = ((Store)e.nextElement()).getId();
                            }
                            
                            //Minorista
                            storesShopKeeper = new StoreList(shopKeeper);
                            storesShopKeeperView = new StoreListViewShopKeeper(storesShopKeeper);
                            e = storesShopKeeper.getStores().elements();
                            if(e.hasMoreElements()){
                                storeShopKeeper = ((Store)e.nextElement()).getId();
                            }  

                        }else if(combo.equals("shopKeeper")){
                            storesShopKeeper = new StoreList(shopKeeper);
                            storesShopKeeperView = new StoreListViewShopKeeper(storesShopKeeper);
                            Enumeration e = storesShopKeeper.getStores().elements();
                            if(e.hasMoreElements()){
                                storeShopKeeper = ((Store)e.nextElement()).getId();
                            }  
                            
                            //Proveedor
                            communities = new CommunityList(supplier);
                            communitiesView = new CommunityListView(communities);
                            e = communities.getCommunities().elements();
                            if(e.hasMoreElements()){
                                community = ((Community)e.nextElement()).getId();
                                storesSupplier = new StoreList();
                                storesSupplier.getCommunityStores(-1, community);
                                storesSupplierView = new StoreListViewSupplier(storesSupplier);
                                e = storesSupplier.getStores().elements();
                                if(e.hasMoreElements()){
                                    storeSupplier = ((Store)e.nextElement()).getId();
                                }
                            }
                            
                        }else if(combo.equals("button")){
                            communities = new CommunityList(supplier);
                            communitiesView = new CommunityListView(communities);
                            Enumeration e = communities.getCommunities().elements();
                            if(e.hasMoreElements()){
                                community = ((Community)e.nextElement()).getId();
                                storesSupplier = new StoreList();
                                storesSupplier.getCommunityStores(-1, community);
                                storesSupplierView = new StoreListViewSupplier(storesSupplier);
                                e = storesSupplier.getStores().elements();
                                if(e.hasMoreElements()){
                                    storeSupplier = ((Store)e.nextElement()).getId();
                                }
                            }
                            
                            //Minorista
                            storesShopKeeper = new StoreList(shopKeeper);
                            storesShopKeeperView = new StoreListViewShopKeeper(storesShopKeeper);
                            e = storesShopKeeper.getStores().elements();
                            if(e.hasMoreElements()){
                                storeShopKeeper = ((Store)e.nextElement()).getId();
                            }  
                            
                        }
                        
                        date=Integer.parseInt(request.getParameter("date"));
                    
                        
                        //companyType -> 1:minorista, 2:proveedor
                        companyType = Integer.parseInt(request.getParameter("companyType"));
                        if(companyType==1){
                            supplierSql=-1;
                            communitySql=-1;
                            storeSupplierSql=-1;
                            shopKeeperSql=shopKeeper;
                            storeShopKeeperSql=storeShopKeeper;
                        }else if(companyType==2){
                            shopKeeperSql=-1;
                            storeShopKeeperSql=-1;
                            supplierSql=supplier;
                            communitySql=community;
                            storeSupplierSql=storeSupplier;
                        }

                        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" ) );
                        pageResults = ( pageResults < 1 ) ? 20 : pageResults;
                }catch( Exception e ){
                    System.out.println( "Excepcion en el servlet de reportes --> " + e);
                }
                
                if(supplierSql>-1){
                    reportList = new ReportOrderList(shopKeeperSql,supplierSql,storeSupplierSql,communitySql,orderCriteria,transactionType,superOffer,"","",startDate,endDate);
                }else{
                    reportList = new ReportOrderList(shopKeeperSql,supplierSql,storeShopKeeperSql,communitySql,orderCriteria,transactionType,superOffer,"","",startDate,endDate);
                }
                
                // aqui se efectua la paginación
                list=reportList.getOrderList();
                System.out.println(list.getOrders().size());
                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 tempOrders = new Vector(); 
                for(int i=0;i<total;i++){
                    if(i>=firstRow && i<=lastRow-1){
                        tempOrders.addElement(list.getOrders().elementAt(i));
                    }
                }
                
                list.setOrders(tempOrders);
                view = new OrderListViewSysManager( list );                
            }else{
                //reportList = new ReportOrderList(shopKeeper,supplier,storeSupplier,community,orderCriteria,orderStatus,superOffer,"","",startDate,endDate);
                //list=reportList.getOrderList();
                list = new OrderList();
                list.setOrders(new Vector());
                view = new OrderListViewSysManager( list );                
                
                //Proveedor
                Enumeration e = suppliers.getSuppliers().elements();
                if(e.hasMoreElements()){
                    supplier = ((Supplier)e.nextElement()).getSupplierId();
                    
                    communities = new CommunityList(supplier);
                    communitiesView = new CommunityListView(communities);
                    e = communities.getCommunities().elements();
                    if(e.hasMoreElements()){
                        community = ((Community)e.nextElement()).getId();
                        storesSupplier = new StoreList();
                        storesSupplier.getCommunityStores(-1, community);
                        storesSupplierView = new StoreListViewSupplier(storesSupplier);
                        e = storesSupplier.getStores().elements();
                        if(e.hasMoreElements()){
                            storeSupplier = ((Store)e.nextElement()).getId();
                        }
                    }
                }
                
                //Minorista
                e = shopKeepers.getShopKeepers().elements();
                if(e.hasMoreElements()){
                    shopKeeper = ((ShopKeeper)e.nextElement()).getShopKeeperId();
                    storesShopKeeper = new StoreList(shopKeeper);
                    storesShopKeeperView = new StoreListViewShopKeeper(storesShopKeeper);
                    e = storesShopKeeper.getStores().elements();
                    if(e.hasMoreElements()){
                        storeShopKeeper = ((Store)e.nextElement()).getId();
                    }  
                }  
            }
            
            request.setAttribute( "suppliers", suppliersView );
            request.setAttribute( "communities", communitiesView );
            request.setAttribute( "shopKeepers", shopKeepersView );
            request.setAttribute( "storesSupplier", storesSupplierView );
            request.setAttribute( "storesShopKeeper", storesShopKeeperView );
            request.setAttribute( "view", view );
            
            // información de los criterios de búsqueda
            request.setAttribute( "supplier", supplier + "" ) ;
            request.setAttribute( "shopKeeper", shopKeeper + "" );
            request.setAttribute( "community", community + "" ) ;
            request.setAttribute( "storeSupplier", storeSupplier + "" ) ;
            request.setAttribute( "storeShopKeeper", storeShopKeeper + "" ) ;
            //request.setAttribute( "order", order + "" ) ;
            //request.setAttribute( "historical", Boolean.toString(historical) );
            request.setAttribute( "superOffer", superOffer + "" );
            request.setAttribute( "transactionType", transactionType + "" );
            
            /// 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 + "" );

            url = "/administrador/reportespedidos.jsp";
        }
        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";
    }
    
    
    
}
