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.Customer;
import edu.uprm.ece.icom5016.bean.ShoppingCart;
import edu.uprm.ece.icom5016.util.ActiveAccounts;

/**
 * @version 	1.0
 * @author
 */
public class LoginServlet 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 {
		//Get session
		HttpSession session = req.getSession(true);
		//RequestDispatcher dispatcher = null;//req.getRequestDispatcher("/icom5016/login.jsp");
		String user = req.getParameter("user");
		String pass = req.getParameter("pass");
		String red_url = "/icom5016/login.jsp";
		if((user != null ) && (pass != null)){
			//Should access a database here
			if(ActiveAccounts.isActive(user)){
				//User is authenticated
				//Set the info that states that the user is logged
				session.setAttribute("customer", new Customer(user));
				//check which jsp should be invoked
				if(session.getAttribute("checkout") != null){
					//req.removeAttribute("checkout");
					session.removeAttribute("checkout");
					red_url = "/icom5016/checkout.jsp";
					//dispatcher = req.getRequestDispatcher("/icom5016/checkout.jsp");
				}else{
					//Check if cart exists
					ShoppingCart cart = (ShoppingCart) session.getAttribute("cart");
					if(cart == null){
						//Create the cart
						session.setAttribute("cart", new ShoppingCart());
					}
					red_url = "/icom5016/index.jsp";
					//dispatcher = req.getRequestDispatcher("/icom5016/index.jsp");	
				}
			}
		}
//		}else{
//			red_url = "/icom5016/login.jsp";
//			//dispatcher = req.getRequestDispatcher("/icom5016/login.jsp");
//		}
		//dispatcher.forward(req, resp);
		resp.sendRedirect(red_url);
	}

	/**
	* @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();

	}

}
