/*
 * TopReportsView.java
 *
 * Created on 4 de abril de 2005, 10:36 AM
 */

package com.fenalco.servlets.shopkeeper;

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

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

import java.sql.Date;
import java.util.Vector;
import java.util.Hashtable;
import java.util.Enumeration;

import com.fenalco.entities.DataAccess;
import com.fenalco.entities.User;
import com.fenalco.entities.ReportDataAccess;
import com.fenalco.entities.SupplierList;
import com.fenalco.entities.Supplier;
import com.fenalco.entities.StoreList;
import com.fenalco.entities.ShopKeeper;

import com.fenalco.utilities.MessageBuilder;
import com.fenalco.utilities.lists.SupplierListViewSysManager;
//import com.fenalco.utilities.lists.StoreListViewSysManager;
import com.fenalco.utilities.lists.TopReportListView;

/**
 *
 * @author  Juan Ernesto Peña Kaltekis
 * @version
 */
public class TopReportsView 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 ){
                url = "/index.jsp";
                message = MessageBuilder.buildMessage(15);
            }else{
                
                // 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
                
                Vector list = new Vector();
                TopReportListView view = new TopReportListView();
                String reportTitle;

                int companyId = ((User)session.getAttribute("user")).getCompanyId();  
                int companyTypeId = 1;  //Minorista 
                int supplier = -1;
                int sort = 0;
                int reportType = 1;
                
                Date startDate = new Date(0);
                Date endDate = new Date(0);
                String startDateReturn = "";
                String endDateReturn = "";

                double totalValue = 0;   //Sumatoria del valor de los pedidos                
                
                boolean flag = true;

                if( request.getParameter("reportType") != null){

                    /*
                    System.out.println("CompanyType: "+companyTypeId);
                    System.out.println("CompanyId: "+companyId);
                    */
                    if( request.getParameter("supplier") != null ){
                        supplier = new Integer( request.getParameter("supplier") ).intValue();
                    }

                    if( !request.getParameter("sort").equals("") ){
                        sort = new Integer( request.getParameter("sort") ).intValue();
                    }

                    if( !request.getParameter("reportType").equals("") ){
                        reportType = new Integer( request.getParameter("reportType") ).intValue();
                    }

                    //Inicio de las fechas
                    
                    if( !request.getParameter("startDate").equals("") || !request.getParameter("endDate").equals("")){
                        if(!request.getParameter("startDate").equals("")){
                            try{
                                startDate = Date.valueOf(request.getParameter("startDate"));
                                startDateReturn = request.getParameter("startDate");
                            }catch(Exception e){
                                startDate = new Date(0);
                            }    
                        }    
                        if( !request.getParameter("endDate").equals("")){
                            try{
                                endDate = Date.valueOf(request.getParameter("endDate"));
                                endDateReturn = request.getParameter("endDate");
                            }catch(Exception e){
                                endDate = new Date(0);
                                startDateReturn = "";
                            }    
                        }
                    }
                    
                    //Fin de la fechas


                    list = ReportDataAccess.topReportBuilder( companyId, companyTypeId, sort, 0, reportType, startDate, endDate );
                }else{
                    list = ReportDataAccess.topReportBuilder( -1, companyTypeId, sort, 0, reportType, startDate, endDate );
                }

                // aqui se efectua la paginación
                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;
                }

                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 ){
                                totalValue += ((Double)((Vector)list.elementAt(i)).elementAt(2)).doubleValue(); //Hago la sumatoria
                                temp.addElement(list.elementAt(i));
                        }
                }

                list = temp;
                
                view = new TopReportListView( list );
                
                
                if( reportType == 1){
                    reportTitle = "PRODUCTOS M&Aacute;S COMPRADOS";
                }else{  
                    reportTitle = "COMPRAS POR PROVEEDOR";
                }

                request.setAttribute( "view", view );
                request.setAttribute( "reportTitle",reportTitle );

                SupplierList suppliers = new SupplierList();
                //StoreList stores = new StoreList(companyId);
                SupplierListViewSysManager suppliersView = new SupplierListViewSysManager( suppliers );
                //StoreListViewSysManager storesView = new StoreListViewSysManager( shopKeepers );

                request.setAttribute( "suppliersView", suppliersView );
                //request.setAttribute( "storesView", storesView);

                request.setAttribute( "startDate", startDateReturn);
                request.setAttribute( "endDate", endDateReturn);
                
                request.setAttribute( "sort", new Integer(sort) );
                request.setAttribute( "reportType", new Integer(reportType) );
                request.setAttribute( "companyId", new Integer(companyId) );
                request.setAttribute( "supplier", new Integer(supplier) );
                request.setAttribute( "totalValue", DataAccess.getCurrency(totalValue) );

                /// 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 = "/minorista/reportestop.jsp";
                
            }
        }catch( Exception e ){
            //System.out.println("Error-> "+e);
            e.printStackTrace();
            url="/logout";
            message = MessageBuilder.buildMessage(15);
        }

        request.setAttribute("message", message);
        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
        dispatcher.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";
    }
    
}
