/*
 * LogisticOperatorHandler.java
 *
 * Created on 15 de septiembre de 2004, 15:20
 */

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.LogisticOperator;
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 LogisticOperatorHandler 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
	 *            servlet request
	 * @param response
	 *            servlet response
	 */
	protected void processRequest( HttpServletRequest request,
			HttpServletResponse response ) throws ServletException, IOException
	{

		String url = "";
		String message = MessageBuilder.buildMessage(4);
		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("new") )
				{
					if( !newLogisticOperator(request) )
					{
						message = MessageBuilder.buildMessage(7);
					}
					else
					{
						Log log = new Log();
						String userId = ((User) session.getAttribute("user"))
								.getLogin();
						String numberId = ((User) session.getAttribute("user"))
								.getIdentificationNumber();
						String description = "Nuevo operador log&iacute;stico";
						Transaction t = new Transaction();
						log.saveData(userId, numberId, 36, description, "", t);
						t.execute();
					}
	
				}
				else
					if( operationType.equals("delete") )
					{
	
						String[] items = request.getParameterValues("item");
	
						if( items != null )
						{
							Transaction transaction = new Transaction();
	
							for( int i = 0; i < items.length; i++ )
							{
								LogisticOperator logisticOperator = new LogisticOperator();
								logisticOperator.setId(Integer.parseInt(items[i]));
	
								logisticOperator.delete(transaction);
							}
	
							if( !transaction.execute() )
							{
								message = MessageBuilder.buildMessage(8);
							}
							else
							{
								Log log = new Log();
								String userId = ((User) session
										.getAttribute("user")).getLogin();
								String numberId = ((User) session
										.getAttribute("user"))
										.getIdentificationNumber();
								String description = "Eliminar operadores";
								Transaction t = new Transaction();
								log.saveData(userId, numberId, 38, description, "",
										t);
								t.execute();
							}
						}
						else
						{
							message = "";
						}
	
					}
					else
						if( operationType.equals("update") )
						{
	
							if( !updateLogisticOperator(request) )
							{
								message = MessageBuilder.buildMessage(7);
							}
							else
							{
								Log log = new Log();
								String userId = ((User) session
										.getAttribute("user")).getLogin();
								String numberId = ((User) session
										.getAttribute("user"))
										.getIdentificationNumber();
								String description = "Modificar operador->"
										+ request.getParameter("key");
								Transaction t = new Transaction();
								log.saveData(userId, numberId, 37, description, "",
										t);
								t.execute();
							}
						}
				url = "/administrador/listaoperadoreslogisticos";
			}
	    }
	    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
	 *            servlet request
	 * @param response
	 *            servlet response
	 */
	protected void doGet( HttpServletRequest request,
			HttpServletResponse response ) throws ServletException, IOException
	{
		processRequest(request, response);
	}

	/**
	 * Maneja el método HTTP <code>POST</code>
	 * 
	 * @param request
	 *            servlet request
	 * @param response
	 *            servlet response
	 */
	protected void doPost( HttpServletRequest request,
			HttpServletResponse response ) throws ServletException, IOException
	{
		processRequest(request, response);
	}

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

	/**
	 * -Crea un objeto de tipo <CODE>LogisticOperator</CODE> -Toma los datos
	 * necesarios del request y los carga en el objeto -Llama la función
	 * saveData() del objeto
	 * 
	 * @return booleano que indica si se creo el operador logìstico con èxito
	 *         con éxito
	 * @param request
	 *            Objeto request del sistema
	 */
	public boolean newLogisticOperator( HttpServletRequest request )
	{

		LogisticOperator logisticOperator = new LogisticOperator();

		logisticOperator.setName(request.getParameter("name"));
		logisticOperator.setAddress(request.getParameter("address"));
		logisticOperator.setContact(request.getParameter("contact"));
		logisticOperator.setPhoneNumber(request.getParameter("phoneNumber"));
		logisticOperator.setEmail(request.getParameter("email"));
		logisticOperator.setCityId(Integer.parseInt(request
				.getParameter("city")));

		Transaction transaction = new Transaction();
		logisticOperator.saveData(transaction);
		boolean success = transaction.execute();

		return success;
	}

	/**
	 * -Crea un objeto de tipo <CODE>LogisticOperator</CODE> con el id del
	 * usuario que se toma del request -Toma los datos necesarios del request y
	 * los carga en el objeto -Llama la función update() del objeto
	 * 
	 * @return booleano que indica si la actualización fué exitosa
	 * @param request
	 *            Objeto request del servidor
	 */
	public boolean updateLogisticOperator( HttpServletRequest request )
	{

		LogisticOperator logisticOperator = new LogisticOperator(Integer
				.parseInt(request.getParameter("key")));

		logisticOperator.setName(request.getParameter("name"));
		logisticOperator.setAddress(request.getParameter("address"));
		logisticOperator.setContact(request.getParameter("contact"));
		logisticOperator.setPhoneNumber(request.getParameter("phoneNumber"));
		logisticOperator.setEmail(request.getParameter("email"));

		Transaction transaction = new Transaction();
		logisticOperator.update(transaction);
		boolean success = transaction.execute();

		return success;
	}

}