package org.hso.ecommerce.controller.shop;

import org.hso.ecommerce.action.shop.GetRandomArticlesAction;
import org.hso.ecommerce.entities.shop.Article;
import org.hso.ecommerce.repos.shop.ArticleRepository;
import org.hso.ecommerce.repos.warehouse.WarehouseBookingPositionSlotEntryRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/")
public class ShopIndexController {

    @Autowired
    private final ArticleRepository articleRepository = null;

    @Autowired
    private final WarehouseBookingPositionSlotEntryRepository warehouseBookingPositionSlotEntryRepository = null;

    @GetMapping("/")
    public String home() {
        return "redirect:/shop/";
    }

    @GetMapping("/shop/")
    public String shop(Model model, HttpSession session) {

        List<Article> commercialArticles = GetRandomArticlesAction.getRandomArticles(8, articleRepository.getAdvertisedArticles()); //get random advertised Articles
        model.addAttribute("commercialArticles", commercialArticles);

        boolean isLoggedIn = false;
        boolean hasOrders = false;

        if (session != null && session.getAttribute("userId") != null) {    //check if logged in
            long userId = (long) session.getAttribute("userId");
            isLoggedIn = true;

            List<Article> suggestedArticles = articleRepository.getOrderedArticles(userId);
            suggestedArticles = suggestedArticles.size() > 3 ? suggestedArticles.subList(0, 4) : suggestedArticles; //only latest 4 ordered articles
            if (suggestedArticles.size() > 0) {
                model.addAttribute("suggestedArticles", suggestedArticles);
                hasOrders = true;
            }
        }

        model.addAttribute("isLoggedIn", isLoggedIn);
        model.addAttribute("hasOrders", hasOrders);

        return "shop/index";
    }

    @GetMapping("/about")
    public String about() {
        return "about";
    }

    @GetMapping("/terms")
    public String terms() {
        return "terms";
    }

    @GetMapping("/privacy")
    public String privacy() {
        return "privacy";
    }
}
