package sklep.controller;

import java.math.BigDecimal;
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 org.springframework.web.bind.annotation.PostMapping;

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";			
		}
	}
	
	@GetMapping("/products/new")
	public String newProduct() {
		return "product_form";
	}
	
	@GetMapping("/products/{id}/edit")
	public String editProduct(Model model, @PathVariable("id") int productId) {
		Optional<Product> product = productRepository.findById(productId);
		if(product.isPresent()) {
			model.addAttribute("product", product.get());
			return "product_form";
		} else {
			model.addAttribute("product_id", productId);
			return "missing_product";			
		}
	}
	
	@PostMapping({"/products/new", "/products/{id}/edit"})
	public String saveProduct(
			Product product,
			Model model) {
		// W tej wersji dane z wypełnionego formularza odbieramy w postaci jednego obiektu Product.
		// Spring sam wpisze dane do pól o takich samych nazwach.
		// Taki parametr od razu staje się częścią modelu (to jest tzw. ModelAttribute)
		// i nie trzeba dodawać go w osobnym poleceniu.
		
		try {
			System.out.println("Produkt przed zapisem: " + product);
			productRepository.save(product);
			System.out.println("Produkt po zapisie   : " + product);
			model.addAttribute("saved", true);
		} catch(Exception e) {
			System.out.println("Produkt bez zapisu   : " + product);
			model.addAttribute("errors", List.of(e.toString()));
		}
		return "product_form";
	}

}
