package org.hso.ecommerce.controller.shop;

import org.hso.ecommerce.action.shop.SearchByTermAction;
import org.hso.ecommerce.entities.shop.Article;
import org.hso.ecommerce.repos.shop.ArticleRepository;
import org.hso.ecommerce.repos.shop.CategoryRepository;
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.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Controller
@RequestMapping("/shop/search")
public class ShopSearchController {

    @Autowired
    private final ArticleRepository articleRepository = null;

    @Autowired
    private final CategoryRepository categoryRepository = null;

    @GetMapping("")
    public String searchArticles(@RequestParam(required = false, value = "term") String term,
                                 @RequestParam(required = false, value = "category") String category,
                                 Model model,
                                 HttpServletRequest request,
                                 HttpServletResponse response
    ) {
        model.addAttribute("categories", categoryRepository.getCategories());   //for sidebar

        if (term != null) { //if search by Term
            term = term.trim();
            List<Article> articles = SearchByTermAction.searchByTerm(term, articleRepository);
            model.addAttribute("articles", articles);
        } else if (category != null) {  //if search by Category
            List<Article> articles = articleRepository.getArticlesByCategory(category); //search by Category
            model.addAttribute("articles", articles);
        } else {
            request.setAttribute("error", "Es wurden keine Suchparameter angegeben.");
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return "error/404";
        }

        return "/shop/search";
    }
}