/*
 * ComplaintHandler.java
 *
 * Created on 10 de agosto de 2004, 17:55
 */

package com.fenalco.servlets.shopkeeper;

import java.io.IOException;
import java.sql.Date;

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

/**
 * Este servlet procesa la solicitud de envío de una queja del usuario que es
 * diligenciada en reclamos.jsp.
 * 
 * @author Mario Linares Vásquez
 */
public class ComplaintHandler extends HttpServlet
{
	/**
	 * Inicializa el servlet.
	 * 
	 * @param config
	 * @throws ServletException
	 */
	public void init( ServletConfig config ) throws ServletException
	{
		super.init(config);

	}

	/**
	 * Destructor del servlet.
	 */
	public void destroy( )
	{

	}

	/**
	 * Procesa solicitudes para los métodos HTTP <code>GET</code> y
	 * <code>POST</code>. En este caso invoca el método <CODE>
	 * submitComplaint</CODE> para generar la queja
	 * 
	 * @param request
	 *            servlet request
	 * @param response
	 *            servlet response
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void processRequest( HttpServletRequest request,
			HttpServletResponse response ) throws ServletException, IOException
	{
        HttpSession session = request.getSession( false );
        String message = "";
		String url = "/minorista/minorista";
	    try
	    {
	        if( session != null && ( User )session.getAttribute( "user" ) != null && ( ( User )session.getAttribute( "user" ) ).getRoleId() == 3 )
			{
	
				if( this.submitComplaint(request) )
				{
					message = MessageBuilder.buildMessage(21);
				}
				else
				{
					message = MessageBuilder.buildMessage(20);
				}
	
			}
			else
			{
				message = MessageBuilder.buildMessage(15);
				url = "index.jsp";
			}
	    }
	    catch( Exception e )
	    {
	        url="/logout";
	        message = MessageBuilder.buildMessage(15);
	    }
		request.setAttribute("message", message);
		RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
		dispatcher.forward(request, response);

	}

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

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

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

	/**
	 * Este método construye una instancia de la clase Complaint con el
	 * constructor vacío y fija los atributos de este con los enviados en el
	 * formulario en el request luego de fijados los atributos utiliza la
	 * función saveData y retorna true si el proceso fué exitoso
	 * 
	 * @param request
	 *            Request enviado al servlet
	 * @return boolean que representa el exito del proceso
	 */
	public boolean submitComplaint( HttpServletRequest request )
	{
		boolean flag = true;
		Transaction transaction = new Transaction();
		int categoryId;
		String cat = request.getParameter("category");
		if( cat == null )
		{
			categoryId = 1;
		}
		else
		{
			categoryId = Integer.parseInt(cat);
		}

		ComplaintCategory category = new ComplaintCategory(categoryId);
		Complaint complaint = new Complaint();
		User user = (User) request.getSession().getAttribute("user");

		complaint.setCategoryId(categoryId);
		complaint.setCategoryName(category.getName());
		complaint.setContent(request.getParameter("message"));

		complaint.setDate(new Date((new java.util.Date()).getTime()));
		complaint.setDestinationEmail(category.getEmail());
		complaint.setUserId(user.getLogin());
		complaint.setUserName(user.getFirstName() + " " + user.getLastName());

		flag = complaint.submitComplaint(transaction);

		// almaceno el reclamo en el log
		if( flag )
		{
			HttpSession session = request.getSession();
			try
			{
				Transaction t = new Transaction();
				Log l = new Log();
				String userId = user.getLogin();
				String numberId = user.getIdentificationNumber();
				String externalUser = "";
				String description = "Envio de Reclamo";
				User callcenter = (User) session.getAttribute("callcenter");
				if( callcenter != null )
				{
					externalUser = callcenter.getLogin();
				}
				l.saveData(userId, numberId, 8, description, externalUser, t);
				t.execute();
			}
			catch (Exception ex)
			{
				System.out.println("Error guardando el Log.");
			}

		}

		return flag;
	}

}