package com.nisum.servlet;

import com.nisum.dao.CartDAO;
import com.nisum.model.CartItem;
import com.nisum.model.ShoppingCart;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;


public class CartServlet extends HttpServlet {

    private CartDAO cartDAO = new CartDAO();

    @Override

    protected void doGet(HttpServletRequest req, HttpServletResponse resp)

            throws ServletException, IOException {

        int userId = 1; // For now, hardcoded (add session later)

        try {

            System.out.println("In cart Servlet");
            ShoppingCart cart = cartDAO.getOrCreateCart(userId);

            List<CartItem> items = cartDAO.getCartItems(userId);

            req.setAttribute("cartTotal", cart.getCartTotal().doubleValue());
            req.setAttribute("userId", userId);
            req.setAttribute("cartId", cart.getCartId());
            req.setAttribute("cartItems", items);
            //System.out.println(items);
            req.getRequestDispatcher("/jsp/cart.jsp").forward(req, resp);

        } catch (SQLException e) {

            throw new ServletException("Error loading cart", e);

        }

    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        int userId = 1;
        int productId = Integer.parseInt(req.getParameter("productId"));
        int quantity = Integer.parseInt(req.getParameter("quantity"));
        try {
            ShoppingCart cart = cartDAO.getOrCreateCart(userId);
            cartDAO.addToCart(cart.getCartId(), productId, quantity);
            resp.sendRedirect("cart");
        } catch (SQLException e) {
            throw new ServletException("Failed to add item", e);
        }
    }
}

