package sklep.controller;

import java.math.BigDecimal;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;

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 org.springframework.web.bind.annotation.RequestParam;

import sklep.model.Product;

@Controller
@RequestMapping("/alt2")
public class AlternatywneProdukty2 {
	@Autowired
	private EntityManager em;
		
	@GetMapping("/products")
	public String products(Model model) {
		TypedQuery<Product> query = em.createNamedQuery("Product.findAll", Product.class);
		List<Product> products = query.getResultList();
		model.addAttribute("products", products);
		return "products";
	}
	
	@GetMapping("/products/{id}")
	public String oneProduct(Model model, @PathVariable int id) {
		Product product = em.find(Product.class, id);
		model.addAttribute("product", product);
		return "product";
	}
	
	@GetMapping("/by_price")
	public String byPrice(Model model,
			@RequestParam(defaultValue = "0") BigDecimal min,
			@RequestParam(defaultValue = "999999999") BigDecimal max) {
		String ql = "SELECT p FROM Product p WHERE p.price BETWEEN :min AND :max ORDER BY p.productId";
		TypedQuery<Product> query = em.createQuery(ql, Product.class);
		query.setParameter("min", min);
		query.setParameter("max", max);
		List<Product> products = query.getResultList();
		model.addAttribute("products", products);
		return "products";
	}
	
}
