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.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 org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import sklep.model.Product;
import sklep.photo.PhotoUtil;
import sklep.repository.ProductRepository;

@Controller
@RequestMapping("/products")
public class ProductController {
	@Autowired
	private ProductRepository productRepository;
	
	@Autowired
	private PhotoUtil photoUtil;
	
	@GetMapping
	public String wszystkieProdukty(Model model) {
		List<Product> products = productRepository.findAll();
		model.addAttribute("products", products);
		return "products";
	}
	
	@GetMapping("/{id}")
	public String jedenProdukt(@PathVariable Integer id, Model model) {
		Optional<Product> product = productRepository.findById(id);
		if(product.isPresent()) {
			model.addAttribute("product", product.get());
			return "product";
		} else {
			model.addAttribute("product_id", id);
			return "missing_product";
		}
	}

	@GetMapping(path="/{id}/photo", produces="image/jpeg")
	@ResponseBody
	public byte[] foto(@PathVariable Integer id, Model model) {
		return photoUtil.readBytes(id);
	}
	
	@GetMapping("/new")
	public String nowyProdukt() {
		return "product_form";
	}
	
	@GetMapping("/{id}/edit")
	public String edytujProdukt(@PathVariable Integer id, Model model) {
		Optional<Product> product = productRepository.findById(id);
		if(product.isPresent()) {
			model.addAttribute("product", product.get());
			return "product_form";
		} else {
			model.addAttribute("product_id", id);
			return "missing_product";
		}
	}

	@PostMapping({ "/new", "/{id}/edit" })
	public String zapiszProdukt(Model model, Product product) {
		// 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)
		
		System.out.println("Obiekt przed zapisem: " + product.getProductId() + " " + product.getProductName());
		productRepository.save(product);
		System.out.println("Obiekt po zapisie: " + product.getProductId() + " " + product.getProductName());
		return "product_form";
	}
}
