/*
 * OrderListHandler.java
 *
 * Created on 17 de septiembre de 2004, 15:30
 */

package com.fenalco.servlets.sysmanager;

import java.io.IOException;

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.Log;
import com.fenalco.entities.Order;
import com.fenalco.entities.OrderList;
import com.fenalco.entities.User;
import com.fenalco.utilities.MessageBuilder;
import com.fenalco.utilities.database.Transaction;

/**
 * 
 * @author Juan Ernesto Peña Kaltekis
 * @version
 */
public class OrderListHandler 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>.
	 * 
	 * @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
			{
	
				String operationType = request.getParameter("operationType");
	
				if( operationType.equals("history") )
				{
	
					String[] items = request.getParameterValues("item");
					if( items != null )
					{
						if( setHistoricalOrders(request) )
						{
							message = MessageBuilder.buildMessage(4);
							Log log = new Log();
							String userId = ((User) session.getAttribute("user"))
									.getLogin();
							String numberId = ((User) session.getAttribute("user"))
									.getIdentificationNumber();
							String description = "Marcar pedidos como hist&oacute;ricos";
							Transaction t = new Transaction();
							log.saveData(userId, numberId, 39, description, "", t);
							t.execute();
						}
						else
						{
							message = MessageBuilder.buildMessage(8);
						}
					}
				}
				url = "/administrador/listapedidos";
			}
	    }
	    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";
	}

	public boolean setHistoricalOrders( HttpServletRequest request )
	{
		OrderList orderList = new OrderList();
		boolean success = true;

		String[] items = request.getParameterValues("item");
		if( items != null )
		{
			Transaction transaction = new Transaction();
			for( int i = 0; i < items.length; i++ )
			{
				Order order = new Order(Integer.parseInt(items[i]));
				order.makeHistorical(transaction);
			}
			success = transaction.execute();
		}
		return success;
	}

}