package com.wxpn.tutorial.ec.servlet;

import java.io.IOException;
import java.util.Collection;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.wxpn.tutorial.ec.bean.ECBookMgr;
import com.wxpn.tutorial.ec.bean.ECOrderItem;
import com.wxpn.tutorial.ec.bean.ECOrderItemMgr;

/**
 * Servlet implementation class for Servlet: UserListServlet
 */
public class ShopCartServlet extends javax.servlet.http.HttpServlet implements
		javax.servlet.Servlet {
	/*
	 * (non-Java-doc)
	 * 
	 * @see javax.servlet.http.HttpServlet#HttpServlet()
	 */
	public ShopCartServlet() {
		super();
	}

	/*
	 * (non-Java-doc)
	 * 
	 * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request,
	 *      HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);

		if ((request.getSession() == null)
				|| (request.getSession().getAttribute("username") == null)) {
			response.sendRedirect("/ECommerce/member/login.jsp");
		} else {
			ECOrderItemMgr mgr = new ECOrderItemMgr();
			if ((request.getParameter("action") != null)
					&& (request.getParameter("action").equals("addcart"))) {
				String bookid = request.getParameter("bookid");
				ECOrderItem orderitem = new ECOrderItem();
				orderitem.setUsername(request.getSession().getAttribute(
						"username").toString());
				orderitem.setBookid(Integer.parseInt(bookid));
				ECBookMgr bookMgr = new ECBookMgr();
				orderitem.setGoods_price(bookMgr.get(Integer.parseInt(bookid))
						.getPrice());

				mgr.add(orderitem);
			}
			String clause = "where username='"
					+ request.getSession().getAttribute("username").toString()
					+ "' and status=0";

			Collection c = mgr.getAll(clause);
			request.setAttribute("c", c);
			try {
				if (request.getParameter("url") == null) {
					System.out.println(clause);
					request.getRequestDispatcher("/book_store/cart.jsp")
							.forward(request, response);
				} else {
					request.getRequestDispatcher(request.getParameter("url"))
							.forward(request, response);
				}
			} catch (Throwable t) {
				getServletContext().log(t.getMessage());
			}
		}
	}
}