package br.com.senacagil.shopping.servlets;

import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

import br.com.senacagil.shopping.model.CD;

public class ShoppingServlet extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public void init(ServletConfig conf) throws ServletException {
		super.init(conf);
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}
	
	@SuppressWarnings("unchecked")
	public void doPost(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {

		HttpSession session = req.getSession(true);
		if (session == null) {
			res.sendRedirect("http://localhost:8080/jsp-mvc-model2_shoppingcart_war/error.html");
			return;
		}

		String action = req.getParameter("action");
		List<CD> buyList = (List<CD>)session.getAttribute("shopping.shoppingcart");
		
		if (!action.equals("CHECKOUT")) {
			if (action.equals("DELETE")) {
				String del = req.getParameter("delindex");
				int d = (new Integer(del)).intValue();
				buyList.remove(d);
			} else if (action.equals("ADD")) {
				// any previous buys of same cd?
				boolean match = false;
				CD aCD = getCD(req);
				if (buyList == null) {
					// add first cd to the cart
					buyList = new ArrayList<CD>(); // first order
					buyList.add(aCD);
				} else { // not first buy
					int i=0;
					for (CD cd : buyList) {
						if (cd.getAlbum().equals(aCD.getAlbum())) {
							cd.setQuantity(cd.getQuantity()
											+ aCD.getQuantity());
							buyList.set(i, cd);
							match = true;
						} // end of if name matches
						++i;
					} // end of for
					if (!match)
						buyList.add(aCD);
				}
			}
			session.setAttribute("shopping.shoppingcart", buyList);

			String url = "/jsp/EShop.jsp";
			ServletContext sc = getServletContext();
			RequestDispatcher rd = sc.getRequestDispatcher(url);
			rd.forward(req, res);
		} 
		else if (action.equals("CHECKOUT")) 
		{
			float total = 0;
			for (CD anOrder : buyList) {
				float price = anOrder.getPrice();
				int qty = anOrder.getQuantity();
				total += (price * qty);
			}
			total += 0.005;
			String amount = new Float(total).toString();
			int n = amount.indexOf('.');
			amount = amount.substring(0, n + 3);

			req.setAttribute("amount", amount);

			String url = "/jsp/Checkout.jsp";
			ServletContext sc = getServletContext();
			RequestDispatcher rd = sc.getRequestDispatcher(url);
			rd.forward(req, res);
		}
	}

	private CD getCD(HttpServletRequest req) {
		// imagine if all this was in a scriptlet...ugly, eh?
		String myCd = req.getParameter("CD");
		String qty = req.getParameter("qty");
		StringTokenizer t = new StringTokenizer(myCd, "|");
		String album = t.nextToken();
		String artist = t.nextToken();
		String country = t.nextToken();
		String price = t.nextToken();
		price = price.replace('$', ' ').trim();

		CD cd = new CD();
		cd.setAlbum(album);
		cd.setArtist(artist);
		cd.setCountry(country);
		cd.setPrice((new Float(price)).floatValue());
		cd.setQuantity((new Integer(qty)).intValue());

		return cd;
	}
}
