/*
 * DataHandler.java
 *
 * Created on 10 de agosto de 2004, 18:22
 */

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

/**
 * 
 * @author andres
 * @version
 */
public class DataHandler 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>.
	 * 
	 * -Llama la funciòn updateSysManager(request) -Redirecciona a
	 * datosadministrador
	 * 
	 * @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
			{
	
				message = MessageBuilder.buildMessage(4);
				if( !updateSysManager(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 datos del administrador";
					Transaction t = new Transaction();
					log.saveData(userId, numberId, 28, description, "", t);
					t.execute();
				}
				url = "/administrador/datosadministrador";
			}
	
			String login = ((User) session.getAttribute("user")).getLogin();
			session.removeAttribute("user");
	
			User user = new User(login);
			session.setAttribute("user", user);
			request.getSession().setAttribute("user", user);
	    }
	    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";
	}

	/**
	 * -Crea un objeto de tipo <CODE>User</CODE> con el login del usuario que
	 * se toma del request -Carga en el objeto los datos necesarios tomados del
	 * request -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 updateSysManager( HttpServletRequest request )
	{

		User user = new User(request.getParameter("login"));

		String password1 = request.getParameter("password");
		String password2 = request.getParameter("password2");

		boolean success = false;

		user.setFirstName(request.getParameter("firstName"));
		user.setLastName(request.getParameter("lastName"));
		user.setEmail(request.getParameter("email"));
		user.setIdentificationNumber(request
				.getParameter("identificationNumber"));
		user.setPhoneNumber(request.getParameter("phoneNumber"));

		Transaction transaction = new Transaction();

		if( request.getParameterValues("changePassword") != null )
		{
			user.setPassword(request.getParameter("password"));
		}

		user.update(transaction);

		success = transaction.execute();

		return success;
	}
}