/*
 * ShopKeeperReports.java
 *
 * Created on 3 de abril de 2005, 08:42 PM
 */

package com.fenalco.servlets.shopkeeper;

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.SupplierList;
import com.fenalco.entities.StoreList;
import com.fenalco.entities.DataAccess;
import com.fenalco.utilities.MessageBuilder;
import com.fenalco.utilities.lists.OrderListViewSysManager;
import com.fenalco.utilities.lists.SupplierListViewSysManager;
import com.fenalco.utilities.lists.StoreListViewShopKeeper;

import com.fenalco.entities.Supplier;
import com.fenalco.entities.Store;
import com.fenalco.entities.User;

/**
 *
 * @author  Juaner
 * @version
 */
public class ShopKeeperReports 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 || session.getAttribute("user")==null){
            url="/index.jsp";
            message = MessageBuilder.buildMessage(15);
        }else{
            SupplierList suppliers = new SupplierList();
            SupplierListViewSysManager suppliersView = new SupplierListViewSysManager( suppliers );
            StoreList storesShopKeeper = null;
            StoreListViewShopKeeper storesShopKeeperView = null;
            
            Vector tempGroup = new Vector();
            
            /*
            Vector countries = DataAccess.getCountries();
            Vector provinces = new Vector();
            Vector cities = new Vector();
            Vector zones = new Vector();

            int countryId = 1;
            int provinceId = 1;
            int cityId = 1;
            */
            
            // captura los criterios de búsqueda provenientes del jsp
            int companyType = 1;    //Minorista
            int order = 2;
            int supplier=-1;
            int shopKeeper=((User)session.getAttribute("user")).getCompanyId();
            int storeShopKeeper=-1;
            int superOffer=0;
            int transactionType = 1;

            String operation="";
            String groupBy="";
            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")));
                        }
                        
                        if(request.getParameter("supplier")!=null){
                            supplier=Integer.parseInt(request.getParameter("supplier"));                        
                            System.out.println("supplier->"+Integer.parseInt(request.getParameter("supplier")));
                        }    

                        //Minorista
                        if(request.getParameter("storeShopKeeper")!=null){
                            storeShopKeeper=Integer.parseInt(request.getParameter("storeShopKeeper"));
                            System.out.println("storeShopKeeper->"+Integer.parseInt(request.getParameter("storeShopKeeper")));
                        }
                        
                        
                        suppliers = new SupplierList(storeShopKeeper);
                        suppliersView = new SupplierListViewSysManager(suppliers);
                        
                        if(combo.equals("storeShopKeeper")){
                            Enumeration e = suppliers.getSuppliers().elements();
                            if(e.hasMoreElements()){
                                supplier = ((Supplier)e.nextElement()).getSupplierId();
                            }
                        }    

                        //Minorista
                        storesShopKeeper = new StoreList(shopKeeper);
                        storesShopKeeperView = new StoreListViewShopKeeper(storesShopKeeper);
                        /*Enumeration e = storesShopKeeper.getStores().elements();
                        if(e.hasMoreElements()){
                            storeShopKeeper = ((Store)e.nextElement()).getId();
                        }*/ 
                            
                        
                        date=Integer.parseInt(request.getParameter("date"));
                        

                        companyType = 1; //Minorista
                        supplierSql=supplier;
                        communitySql=-1;
                        storeSupplierSql=-1;
                        shopKeeperSql=shopKeeper;
                        storeShopKeeperSql=storeShopKeeper;


                        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;
                            }
                        }
                        
                        if(request.getParameter("operation")!=null && companyType!=0){
                            operation="SUM(prod_pedi_cantidad*prod_pedi_precio)";
                            groupBy="pedido.empr_id";
                        }
                        //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);
                }
                
                String role="ShopKeeper";
                
                if(combo.equals("button")){
                    reportList = new ReportOrderList(role,shopKeeperSql,supplierSql,storeShopKeeperSql,communitySql,orderCriteria,transactionType,superOffer,groupBy,operation,startDate,endDate);
                }else{
                    reportList = new ReportOrderList();
                }
                    
                // aqui se efectua la paginación
                list=reportList.getOrderList();
                //System.out.println(list.getOrders().size());
                Vector group = reportList.getGroup();
                
                if(operation.equals("")){
                    total = list.getOrders().size();
                }else{
                    total = group.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(); 
                if(operation.equals("")){
                    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{
                    for(int i=0;i<total;i++){
                        if(i>=firstRow && i<=lastRow-1){
                            tempGroup.addElement(group.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();
                storesShopKeeper = new StoreList(shopKeeper);
                storesShopKeeperView = new StoreListViewShopKeeper(storesShopKeeper);
                Enumeration e = storesShopKeeper.getStores().elements();
                if(e.hasMoreElements()){
                    storeShopKeeper = ((Store)e.nextElement()).getId();
                    suppliers = new SupplierList(storeShopKeeper);
                    e = suppliers.getSuppliers().elements();
                    if(e.hasMoreElements()){
                        supplier = ((Supplier)e.nextElement()).getSupplierId();
                    }  
                } 
                
                firstRow = 0;
                lastRow = 0;
                total = 0;
                
                list = new OrderList(true);
                view = new OrderListViewSysManager( list );                
            }
            
            request.setAttribute( "suppliers", suppliersView );
            request.setAttribute( "storesShopKeeper", storesShopKeeperView );
            request.setAttribute( "view", view );
            request.setAttribute( "group", tempGroup );
            
            // información de los criterios de búsqueda
            request.setAttribute( "supplier", supplier + "" ) ;
            request.setAttribute( "shopKeeper", shopKeeper + "" );
            request.setAttribute( "storeShopKeeper", storeShopKeeper + "" ) ;
            //request.setAttribute( "order", order + "" ) ;
            //request.setAttribute( "historical", Boolean.toString(historical) );
            request.setAttribute( "superOffer", superOffer + "" );
            request.setAttribute( "operation", operation ) ;            
            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("storeShopKeeper")!=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( "date", date + "" );

            url = "/minorista/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";
    }
    
}
