package sklep.controller;

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.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import sklep.model.Product;
import sklep.repository.ProductRepository;

import java.util.List;
import java.util.Optional;


@Controller
@RequestMapping("/products")
public class ProductController {
    @Autowired
    private ProductRepository productRepository;

    @GetMapping
    public String readAll(Model model) {
        List<Product> products = productRepository.findAll();
        model.addAttribute("products", products);
        return "products";
    }

    @GetMapping("/{id}")
    public String readOne(@PathVariable("id") Integer productId, Model model) {
        Optional<Product> product = productRepository.findById(productId);
        if(product.isPresent()) {
            model.addAttribute("product", product.get());
            return "product";
        } else {
            return "missing_product";
        }
    }

    @GetMapping("/szukaj")
    public String szukaj(String name, Model model) {
        List<Product> products = productRepository.findByProductName(name);
        model.addAttribute("products", products);
        return "wyszukiwarka";
    }
}
