/*
 * SupplierBillingHandler.java
 *
 * Created on 10 de agosto de 2004, 18:16
 */

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

/**
 * 
 * @author andres
 * @version
 */
public class SupplierBillingHandler 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 del request un id que identifica una factura (billId) y el estado
	 * a asignar (newStatus).
	 * 
	 * -Crea una instancia de un objeto <CODE>Bill</CODE> con el id que
	 * recibió -Asigna el nuevo estado y actualiza. -Redirecciona a
	 * facturacionproveedor
	 * 
	 * @param request
	 *            peticiòn al servlet
	 * @param response
	 *            respuesta del servlet
	 */
	protected void processRequest( HttpServletRequest request,
			HttpServletResponse response ) throws ServletException, IOException
	{

		String message = "";

		String url = "";
		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
			{
				if( request.getParameter("operationType").equals(
						"changeBillingType") )
				{
					int supplierId = Integer.parseInt(request.getParameter("key"));
					Supplier supplier = new Supplier(supplierId);
					supplier.setbillingType(Integer.parseInt(request
							.getParameter("billingType" + supplierId)));
	
					Transaction transaction = new Transaction();
					supplier.update(transaction);
					if( !transaction.execute() )
					{
						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 = "Tipo->"
								+ request.getParameter("billingType" + supplierId)
								+ ",Proveedor->" + supplierId;
						Transaction t = new Transaction();
						log.saveData(userId, numberId, 21, description, "", t);
						t.execute();
					}
	
					url = "/administrador/listaproveedoresfacturacion";
				}
				else
					if( request.getParameter("operationType")
							.equals("changeStatus") )
					{
	
						int billId = Integer.parseInt(request.getParameter("key"));
						int newStatus = Integer.parseInt(request
								.getParameter("status"));
						String supplierId = request.getParameter("supplierId");
	
						Bill bill = new Bill(billId);
						bill.setStatusId(newStatus);
	
						Transaction transaction = new Transaction();
						bill.update(transaction);
						if( !transaction.execute() )
						{
							message = MessageBuilder.buildMessage(7);
						}
	
						url = "/administrador/facturacionproveedor?key="
								+ supplierId + "&operationType=view";
					}
			}
	    }
	    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";
	}

}