/*
 * ComplaintTypeView.java
 *
 * Created on 10 de agosto de 2004, 18:16
 */

package com.fenalco.servlets.sysmanager;

import java.io.IOException;
import java.util.Vector;

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.ComplaintCategoryList;
import com.fenalco.entities.User;
import com.fenalco.utilities.MessageBuilder;
import com.fenalco.utilities.lists.ComplaintCategoryListView;

/**
 * 
 * @author andres
 * @version
 */
public class ComplaintTypeView extends HttpServlet
{

	/**
	 * Inicializa el servlet.
	 */
	public void init( ServletConfig config ) throws ServletException
	{
		super.init(config);

	}

	/**
	 * Destruye el servlet.
	 */
	public void destroy( )
	{

	}

	/**
	 * Procesa las peticiones de los mètodos HTTP <code>GET</code> y
	 * <code>POST</code>.
	 * 
	 * -Crea un objeto de tipo <CODE>ComplaintCategoryList</CODE> -Crea un
	 * objeto de tipo <CODE>ComplaintCategoryListView</CODE> -Manda el objeto
	 * (la vista) en el request -Redirecciona a tiposreclamo.jsp
	 * 
	 * @param request
	 *            peticiòn al servlet
	 * @param response
	 *            respuesta del servlet
	 */
	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() != 1 )
			{
				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
                            
				ComplaintCategoryList complaintCategoryList = new ComplaintCategoryList();
                                
                                // 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 = complaintCategoryList.getCategories().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(complaintCategoryList.getCategories().elementAt(i));
                                        }
                                }
                                
                                complaintCategoryList.setCategories(temp);
                                
				ComplaintCategoryListView view = new ComplaintCategoryListView(
						complaintCategoryList);
	
				request.setAttribute("view", view);
	
				/// 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/tiposreclamo.jsp";
			}
	    }
	    catch( Exception e )
	    {
                System.out.println("Error-> "+e);
	        url="/logout";
	        message = MessageBuilder.buildMessage(15);
	    }

		request.setAttribute("message", message);
		RequestDispatcher dispatcher = getServletContext()
				.getRequestDispatcher(url);
		dispatcher.forward(request, response);

	}

	/**
	 * Maneja el mètodo HTTP <code>GET</code>
	 * 
	 * @param request
	 *            peticiòn al servlet
	 * @param response
	 *            respuesta del servlet
	 */
	protected void doGet( HttpServletRequest request,
			HttpServletResponse response ) throws ServletException, IOException
	{
		processRequest(request, response);
	}

	/**
	 * Maneja el mètodo HTTP <code>POST</code>
	 * 
	 * @param request
	 *            peticiòn al servlet
	 * @param response
	 *            respuesta del servlet
	 */
	protected void doPost( HttpServletRequest request,
			HttpServletResponse response ) throws ServletException, IOException
	{
		processRequest(request, response);
	}

	/**
	 * Retorna una corta descripciòn del servlet.
	 */
	public String getServletInfo( )
	{
		return "Short description";
	}

}