/*
 * PositionHandler.java
 *
 * Created on 30 de septiembre de 2004, 19:43
 */

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.Position;
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 PositionHandler extends HttpServlet
{

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

	}

	/**
	 * Destruye el 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() != 1 )
			{
				url = "/index.jsp";
				message = MessageBuilder.buildMessage(15);
			}
			else
			{
				message = MessageBuilder.buildMessage(4);
				String operationType = request.getParameter("operationType");
	
				if( operationType.equals("new") )
				{
	
					if( !newPosition(request) )
					{
						message = MessageBuilder.buildMessage(7);
					}
	
				}
				else
					if( operationType.equals("update") )
					{
	
						if( !updatePosition(request) )
						{
							message = MessageBuilder.buildMessage(7);
						}
	
					}
					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++ )
								{
	
									Position position = new Position();
									position.setId(Integer.parseInt(items[i]));
	
									position.delete(transaction);
								}
								if( !transaction.execute() )
								{
									message = MessageBuilder.buildMessage(8);
								}
							}
							else
							{
								message = "";
							}
						}
				url = "/administrador/listacargos";
			}
	    }
	    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);
	}

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

	/**
	 * -Crea un objeto de tipo <CODE>Position</CODE> con el id del parámetro
	 * 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 updatePosition( HttpServletRequest request )
	{

		Position position = new Position(Integer.parseInt(request
				.getParameter("key")));

		String variableName = "name" + request.getParameter("key");
		position.setName(request.getParameter(variableName));

		Transaction transaction = new Transaction();
		position.update(transaction);

		boolean success = transaction.execute();

		return success;
	}

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

		Position position = new Position();

		position.setName(request.getParameter("name"));

		Transaction transaction = new Transaction();
		position.saveData(transaction);

		boolean success = transaction.execute();

		return success;
	}

}