package org.hso.ecommerce.controller.shop;

import org.hso.ecommerce.entities.shop.Article;
import org.hso.ecommerce.entities.shop.ShoppingCart;
import org.hso.ecommerce.repos.shop.ArticleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

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

@Controller
@RequestMapping("/shop/articles")
public class ShopArticleController {

    @Autowired
    private final ArticleRepository articleRepository = null;

    @GetMapping("/{id}")
    public String shopArticlesById(Model model, @PathVariable("id") Integer Id) {

        //TODO: Get Article by Id instead of this dummy shit
        Article d1 = new Article();
        d1.description = "this is dummy1";
        d1.title = "dummy1";
        d1.shopPricePerUnitNetCent = 1500;
        d1.id = 1234;

        model.addAttribute("article", d1);

        //TODO: Check if in Stock
        if(false){
            model.addAttribute("inStock", true);
        }else{
            model.addAttribute("inStock", false);
        }

        //TODO: Get 2 Commercialised Articles
        List<Article> commercialArticles = new ArrayList<Article>();
        Article d2 = new Article();
        d2.description = "this is dummy2";
        d2.title = "dummy2";
        d2.shopPricePerUnitNetCent = 2000;
        d2.id = 2345;
        Article d3 = new Article();
        d3.description = "this is dummy3";
        d3.title = "dummy3";
        d3.shopPricePerUnitNetCent = 2500;
        d3.id = 3456;
        commercialArticles.add(d2);
        commercialArticles.add(d3);
        model.addAttribute("commercialArticles", commercialArticles);

        return "shop/articles/id";
    }

    @PostMapping("/{id}")
    public String shopArticlesByIdBuy(HttpSession session,
                                      @RequestAttribute(value = "shoppingCart") ShoppingCart shoppingCart,
                                      @PathVariable("id") Long id,
                                      @RequestParam("quantity") Integer quantity,
                                      @RequestParam("fastcheckout") Boolean fastcheckout
    ) {

        Optional<Article> article = articleRepository.findById(id);
        if (!article.isPresent()) {
            throw new RuntimeException("Article not found!");
        }

        shoppingCart.addArticle(article.get(), quantity);

        if (!fastcheckout) {
            return "shop/articles/post_add";
        } else {
            return "shop/checkout";
        }
    }
}
