/*
 * UserHandler.java
 *
 * Created on 10 de agosto de 2004, 18:23
 */

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.DataAccess;
import com.fenalco.entities.Log;
import com.fenalco.entities.User;
import com.fenalco.utilities.MessageBuilder;
import com.fenalco.utilities.crypto.MD5;
import com.fenalco.utilities.database.Transaction;
import com.fenalco.utilities.mail.MailHandler;

/**
 * 
 * @author andres
 * @version
 */
public class UserHandler 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>.
	 * 
	 * Recibe el parámtero operationType en el request, de acuerdo a su valor se
	 * decide que acción realizar:
	 * 
	 * 1)"new" Llama la función newUser(request)
	 * 
	 * 2)"delete" -Crea un objeto de tipo <CODE>User</CODE> con el id que
	 * recibe en el request -Llama el método delete() del objeto
	 * 
	 * 3)"update" Llama la función updateUser(request)
	 * 
	 * Redirecciona a listausuarios
	 * 
	 * @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 = 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( !newUser(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 usuario";
						Transaction t = new Transaction();
						log.saveData(userId, numberId, 33, 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++ )
							{
								User user = new User();
								user.setLogin(items[i]);
	
								user.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 usuarios";
								Transaction t = new Transaction();
								log.saveData(userId, numberId, 35, description, "",
										t);
								t.execute();
							}
						}
	
					}
					else
						if( operationType.equals("update") )
						{
	
							if( !updateUser(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 usuario->"
										+ request.getParameter("login");
								Transaction t = new Transaction();
								log.saveData(userId, numberId, 34, description, "",
										t);
								t.execute();
							}
						}
				url = "/administrador/listausuarios";
			}
	    }
	    catch( Exception 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> -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 usuario con éxito
	 * @param request
	 *            Objeto request del sistema
	 */
	public boolean newUser( HttpServletRequest request )
	{

		User user = new User();

		user.setLogin(request.getParameter("login"));
		MD5 md5 = new MD5();
		//String password=PasswordHandler.buildRandPasswd();
		String password = "12345";
		System.out.println("pass-> " + password);
		user.setPassword(md5.calcMD5(password));
		System.out.println("passMD5-> " + user.getPassword());
		user.setFirstName(request.getParameter("firstName"));
		user.setLastName(request.getParameter("lastName"));
		user.setIdentificationNumber(request
				.getParameter("identificationNumber"));
		user.setEmail(request.getParameter("email"));
		//user.setIdentificationNumber(request.getParameter("identificationNumber"));
		user.setRoleId(4); //Rol de Callcenter
		user.setPhoneNumber(request.getParameter("phoneNumber"));
		user.setCompanyId(0);
		user.setPositionId(0);

		Transaction transaction = new Transaction();
		user.saveData(transaction);
		boolean success = transaction.execute();
		if( success )
		{
			String content = "Su contraseña para ingresar al sistema es: "
					+ password;
			MailHandler mh = MailHandler.getInstance();
			mh.sendMail(DataAccess.getPvlEmail(), user.getEmail(),
					"contraseña de ingreso al sistema", content);
		}

		return success;
	}

	/**
	 * -Crea un objeto de tipo <CODE>User</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 updateUser( HttpServletRequest request )
	{

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

		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);

		boolean success = transaction.execute();

		return success;
	}

}