/*
 * CartView.java
 *
 * Created on 10 de agosto de 2004, 18:01
 */

package com.fenalco.servlets.shopkeeper;

import com.fenalco.entities.ShoppingCart;
import com.fenalco.entities.User;
import com.fenalco.utilities.MessageBuilder;
import com.fenalco.utilities.lists.ShoppingCartView;
import com.fenalco.entities.PaymentMethodList;
import com.fenalco.entities.PaymentMethod;
import com.fenalco.entities.Store;
import com.fenalco.entities.DataAccess;
import java.io.IOException;
import java.util.Vector;
import java.util.Hashtable;
import java.util.Enumeration;
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;



/**
 * Este servlet carga la información de los productos que el usuario tiene en el
 * carrito de compras y le pasa la lista al jsp para que la pinte
 * 
 * @author Mario Linares Vásquez
 *  
 */
public class CartView extends HttpServlet
{

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

	}

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

	}

	/**
	 * Obtiene de la sesión el carrito de compras y construye los objetos de
	 * tipo producto (clase <CODE>Product</CODE>), los adiciona a un vector y
	 * mete ese vector al <CODE>response</CODE> como un atributo con nombre
	 * <CODE>productsList</CODE>
	 * 
	 * luego redirecciona a /minorista/micarrito.jsp
	 * 
	 * @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 url = "";
		String message = "";

	    try
	    {
	        
	        if( session == null || ( User )session.getAttribute( "user" ) == null || ( ( User )session.getAttribute( "user" ) ).getRoleId() != 3 )
			{
				url = "/index.jsp";
				message = MessageBuilder.buildMessage(15);
			}
			else
			{
				ShoppingCart cart = (ShoppingCart) session.getAttribute("cart");
                                boolean flag = false;
                               /* String supp = request.getParameter("supplier");
                                String payMethod = request.getParameter("payMethod");
                                if(supp != null && payMethod != null){
                                    flag = true;
                                }*/
                                
				if( cart == null )
				{
					cart = new ShoppingCart();
					session.setAttribute("cart", cart);
//					message = "Aún no ha puesto ningún producto en el carrito.";
				}
                                
                                
                                Vector selectedPayments = new Vector();
				ShoppingCartView cartView = new ShoppingCartView(cart);
				request.setAttribute("cartView", cartView);
                                
                                int shopkeeperId = ( ( User )session.getAttribute( "user" ) ).getCompanyId();
                                int storeId = ( ( Store )session.getAttribute( "store" ) ).getId();
                                                                
                                Hashtable suppliersPayments = new Hashtable( );
                                Hashtable suppliers = cart.getProducts();
                                Enumeration suppliersIds = suppliers.keys();
                                while( suppliersIds.hasMoreElements() )
                                {
                                    int id = ( ( Integer )suppliersIds.nextElement() ).intValue();
                                    int communityId = DataAccess.getStoreCommunity( storeId, id );
                                    PaymentMethodList paymentMethodList = new PaymentMethodList( id, shopkeeperId, communityId, 0 );
                                    
                                    /*if( paymentMethodList.getPaymentMethods().size() <= 0 )
                                    {
                                        int communityId = DataAccess.getStoreCommunity( storeId, id );
                                        paymentMethodList = new PaymentMethodList( id, communityId, 2 );
                                        
                                        
                                    }*/

                                    int paymentMethod = ((PaymentMethod) paymentMethodList.getPaymentMethods().elementAt(0)).getId();

                                    /*if(flag && id ==  new Integer(supp).intValue() ){
                                        paymentMethod = new Integer(payMethod).intValue();
                                    }*/
                                    
                                    String tempPay = request.getParameter("payment_"+id);
                                    if(tempPay != null ){
                                        paymentMethod = new Integer(tempPay).intValue();
                                    }


                                    selectedPayments.add( new Integer( paymentMethod ));

                                    suppliersPayments.put( id + "", paymentMethodList );
                                }
                                
                                request.setAttribute( "suppliersPayments", suppliersPayments );
                                request.setAttribute( "selectedPayments", selectedPayments );
                                message = ( String )request.getAttribute( "message" );
				url = "/minorista/micarrito.jsp";
			}
	    }
	    catch( Exception e )
	    {
	        url="/logout";
	        message = MessageBuilder.buildMessage(15);
	    }
	        
        request.setAttribute( "message", message );
        RequestDispatcher rd = getServletContext().getRequestDispatcher( url );
        rd.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 de el servlet.
	 * 
	 * @return
	 */
	public String getServletInfo( )
	{
		return "Short description";
	}

}