/*
 * CompaniesReport.java
 *
 * Created on 22 de julio de 2005, 07:00 PM
 */

package com.fenalco.servlets.sysmanager.reports;

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

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

import com.fenalco.entities.City;
import com.fenalco.entities.CompanyList;
import com.fenalco.entities.DataAccess;
import com.fenalco.entities.Province;
import com.fenalco.entities.SupplierList;
import com.fenalco.entities.User;
import com.fenalco.utilities.lists.SupplierListViewSysManager;
import com.fenalco.utilities.MessageBuilder;

/**
 *
 * @author  Juan Ernesto Peña Kaltekis
 * @version
 */
public class CompaniesReport 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{

                // 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

                SupplierList suppliers = new SupplierList();
                SupplierListViewSysManager suppliersView = new SupplierListViewSysManager( suppliers );
                int companyType = 1;    //Minorista
                int reportType = 1;     //Registrados
                int supplier = -1;
                CompanyList list = new CompanyList(true);

                int date = 1;
                Date startDate = new Date(0);
                Date endDate = new Date(0);
                String startDateReturn = "";
                String endDateReturn = "";
                
                Vector countriesList = DataAccess.getCountries();
                Vector provincesList = new Vector();
                Vector citiesList = new Vector();
                int countryId = 1;
                int provinceId = 1;
                int cityId = 1;
                
                
                //Reviso si es la primera vez
                if(request.getParameter("reportType") != null){
                
                    if( request.getParameter("companyType") != null ){
                        companyType = Integer.parseInt(request.getParameter("companyType"));
                    }

                    if( request.getParameter("reportType") != null ){
                        reportType = Integer.parseInt(request.getParameter("reportType"));
                    }

                    if( request.getParameter("supplier") != null ){
                        supplier = Integer.parseInt(request.getParameter("supplier"));
                    }


                    //Inicio de los combos "geográficos"

                    String combo = request.getParameter("combo");
                    if( combo != null ){

                        countryId = (new Integer(request.getParameter("country"))).intValue();
                        if( request.getParameter("province") != null ){
                            provinceId = (new Integer(request.getParameter("province"))).intValue();
                        }
                        if( request.getParameter("city") != null ){
                            cityId = (new Integer(request.getParameter("city"))).intValue();
                        }

                        provincesList = DataAccess.getProvinces(countryId);
                        if( combo.equals("country") ){
                            provinceId = -1;
                            citiesList = DataAccess.getCities(provinceId);
                            cityId = -1;
                        }else if( combo.equals("province") ){
                            citiesList = DataAccess.getCities(provinceId);
                            cityId = -1;
                        }else{
                            citiesList = DataAccess.getCities(provinceId);
                        }

                    }else{
                        provincesList = DataAccess.getProvinces(countryId);
                        citiesList = DataAccess.getCities(provinceId);
                    }

                    //Fin de los combos "geográficos"

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

                    //Fin de las fechas


                    // 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;
                    }


                    if(reportType==1){
                        list.loadRegisteredCompanies(companyType, cityId, provinceId, countryId, startDate, endDate);
                    }else{
                        list.loadTradingCompanies(companyType, supplier, cityId, provinceId, countryId, startDate, endDate);
                    }

                    total = list.getCompanies().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.getCompanies().elementAt(i));
                        }
                    }

                    list.setCompanies(temp);


                }else{
                    provincesList = DataAccess.getProvinces(countryId);
                    citiesList = DataAccess.getCities(provinceId);
                }
                
                com.fenalco.utilities.lists.CompanyListViewReport view = new com.fenalco.utilities.lists.CompanyListViewReport(list);
                

                request.setAttribute("companyType", companyType + "");
                request.setAttribute("reportType", reportType + "");
                
                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("view", view);
                request.setAttribute( "suppliers", suppliersView );
                request.setAttribute( "supplier", supplier + "" );

                /// 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/empresas.jsp";
                
            }    
        /*}catch( Exception e ){
            System.out.println(e);
            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";
    }
    
}
