package edu.uprm.ece.icom5016.servlet;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
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 edu.uprm.ece.icom5016.bean.CatalogItem;
import edu.uprm.ece.icom5016.bean.ItemOrdered;
import edu.uprm.ece.icom5016.bean.ShoppingCart;
import edu.uprm.ece.icom5016.util.Catalog;

/**
 * @version 	1.0
 * @author
 */
public class AddToCartServlet extends HttpServlet {

	/**
	* @see javax.servlet.GenericServlet#void ()
	*/
	public void destroy() {

		super.destroy();

	}

	/**
	* @see javax.servlet.http.HttpServlet#void (javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	*/
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
		throws ServletException, IOException {
		HttpSession session = req.getSession(true);
		ShoppingCart cart = (ShoppingCart) session.getAttribute("cart");
		ItemOrdered i_ord;
		if(cart == null){
			cart = new ShoppingCart();
			session.setAttribute("cart", cart); 
		}
		//Get item id
		String id = req.getParameter("id");
		//Get number of items
		String n = req.getParameter("qty");
		int num_items;
		if(n == null)
			num_items = 1;
		else
			num_items = Integer.parseInt(n);
		if(num_items <= 0)
			num_items = 1;
		//Check that item is already in the cart
		if(cart.itemExists(id)){
			i_ord = (ItemOrdered) cart.getItem(id);
			i_ord.addItems(num_items);
		}else{
			//Look for item in the catalog
			CatalogItem item = Catalog.getItem(id);
			//Should check if item is available
			i_ord = new ItemOrdered(item, num_items);	
			cart.addItem(i_ord);
		}
		//Forward Request to the ShowCart JSP
		resp.sendRedirect("/icom5016/ShowCart.jsp");
		//RequestDispatcher dispatcher = req.getRequestDispatcher("/ShowCart.jsp");
		//dispatcher.forward(req, resp);
		
	}

	/**
	* @see javax.servlet.http.HttpServlet#void (javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	*/
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
		throws ServletException, IOException {
		this.doGet(req, resp);
	}

	/**
	* @see javax.servlet.GenericServlet#void ()
	*/
	public void init() throws ServletException {

		super.init();

	}

}
