package org.hso.ecommerce.controller.shop;

import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.hso.ecommerce.action.shop.GetRandomArticlesAction;
import org.hso.ecommerce.entities.shop.Article;
import org.hso.ecommerce.entities.shop.ShoppingCart;
import org.hso.ecommerce.repos.shop.ArticleRepository;
import org.hso.ecommerce.repos.shop.CategoryRepository;
import org.hso.ecommerce.repos.warehouse.WarehouseBookingPositionSlotEntryRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

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

    @Autowired
    private final ArticleRepository articleRepository = null;

    @Autowired
    private final WarehouseBookingPositionSlotEntryRepository warehouseBookingPositionSlotEntryRepository = null;

    @Autowired
    private final CategoryRepository categoryRepository = null;

    @GetMapping("/{id}")
    public String shopArticlesById(Model model,
                                   @PathVariable("id") Long id,
                                   HttpServletRequest request,
                                   HttpServletResponse response
    ) {
        model.addAttribute("categories", categoryRepository.getCategories());   //for sidebar

        Article article = articleRepository.findArticleById(id);

        if (article == null) {
            request.setAttribute("error", "Der Artikel wurde nicht gefunden.");
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return "error/404";
        }
        model.addAttribute("article", article);

        if (warehouseBookingPositionSlotEntryRepository.getByArticle(id).get(0).newSumSlot > 0) {   //check if in Stock
            model.addAttribute("inStock", true);
        } else {
            model.addAttribute("inStock", false);
        }

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

        return "shop/articles/id";
    }

    @PostMapping("/{id}")
    public String shopArticlesByIdBuy(HttpServletRequest request,
                                      HttpServletResponse response,
                                      HttpSession session,
                                      @RequestAttribute(value = "shoppingCart") ShoppingCart shoppingCart,
                                      @PathVariable("id") Long id,
                                      @RequestParam("quantity") Integer quantity,
                                      @RequestParam(value = "set_amount", required = false) Boolean setAmount,
                                      @RequestParam("fastcheckout") Boolean fastcheckout
    ) {
        Article article = articleRepository.findArticleById(id);

        if (article == null) {
            request.setAttribute("error", "Der Artikel wurde nicht gefunden.");
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return "error/404";
        }

        if (setAmount != null && setAmount) {
            shoppingCart.setArticleCount(article, quantity);
        } else {
            shoppingCart.addArticle(article, quantity);
        }

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

    @GetMapping("/{id}/image.jpg")
    public void getImageAsByteArray(HttpServletRequest request,
                                    HttpServletResponse response,
                                    @PathVariable("id") Long id
    ) throws IOException {
        Article article = articleRepository.findArticleById(id);
        
        if(article.image != null) {
        	InputStream in = new FileInputStream(article.image.path);
            response.setContentType(MediaType.IMAGE_JPEG_VALUE);
            IOUtils.copy(in, response.getOutputStream());
        }        
    }
}