package sklep.controller;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
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 sklep.model.Product;
import sklep.repository.ProductRepository;

@Controller
public class ProductController {
	@Autowired
	private ProductRepository productRepository;
	
	@GetMapping("/products")
	public String readAllProducts(Model model) {
		List<Product> products = productRepository.findAll(Sort.by("productId"));
		model.addAttribute("products", products);
		
		return "products";
	}
	
	@GetMapping("/products/{id}")
	public String readOneProduct(Model model, @PathVariable("id") int productId) {
		Optional<Product> product = productRepository.findById(productId);
		if(product.isPresent()) {
			model.addAttribute("product", product.get());
			return "product";
		} else {
			model.addAttribute("product_id", productId);
			return "missing_product";			
		}
	}

}
