package com.bookstore.controller.order;

import com.bookstore.bean.Book;
import com.bookstore.bean.Order;
import com.bookstore.bean.OrderBook;
import com.bookstore.bean.User;
import com.bookstore.controller.user.BaseUserController;
import com.bookstore.dao.BookDAO;
import com.bookstore.dao.OrderBookDAO;
import com.bookstore.dao.OrderDAO;
import com.bookstore.dao.UserDAO;
import com.bookstore.util.CartUtil;
import com.bookstore.util.DbUtil;
import com.bookstore.util.UserUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Class CartController
 */
@WebServlet(urlPatterns="/orders/view/*")
public class ViewController extends BaseOrderController {
    @Override
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        UserUtil userUtil = new UserUtil(request.getSession());

        Order order = findResource(request);
        if (order == null) {
            forward404(request, response);
            return;
        }

        // Check permission
        if (!userUtil.isAdmin() && order.getUserId() != userUtil.getUser().getId()) {
            forward403(request, response);
            return;
        }

        OrderBookDAO orderBookDAO = DbUtil.getDAO(OrderBookDAO.class);
        BookDAO bookDAO = DbUtil.getDAO(BookDAO.class);
        UserDAO userDAO = DbUtil.getDAO(UserDAO.class);

        double orderAmount = 0d;

        // Set order books and book detail
        List<OrderBook> orderBookList = orderBookDAO.findAllByOrder(order.getId());
        for (OrderBook book : orderBookList) {
            Book bookDetail;
            if ((bookDetail = bookDAO.find(book.getBookId())) != null) {
                book.setBook(bookDetail);
            } else {
                book.setBook(new Book(0, 0, "Removed Book", "", "", 0, 0, "", ""));
            }
            orderAmount += book.getCount() * book.getBook().getPrice();
        }
        order.setBookList(orderBookList);

        User orderUser = userDAO.find(order.getUserId());

        request.setAttribute("order", order);
        request.setAttribute("orderBookList", orderBookList);
        request.setAttribute("orderAmount", orderAmount);
        request.setAttribute("orderUser", orderUser);
        forward(request, response, "/orders/view.jsp");
    }
}
