package com.example.demo.data;

import java.util.List;

import jakarta.persistence.EntityManager;
import jakarta.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 com.example.demo.model.Employee;

@Controller
@RequestMapping("/emps1")
public class Controller1_EM {
    /* W tej wersji Controller bezpośrednio korzysta z technologii JPA/Hibernate.
     * Ułatwieniem jest to, że Spring automatycznie "wstryknie" nam obiekt EntityManager.
     */
	@Autowired
	private EntityManager em;
	
	@GetMapping
	public String showAll(Model model) {
		TypedQuery<Employee> query = em.createNamedQuery("Employee.findAll", Employee.class);
		List<Employee> emps = query.getResultList();
		model.addAttribute("emps", emps);
		return "employees.html";
	}
	
	@GetMapping("/{id}")
	public String showOne(Model model,
			@PathVariable("id") Integer employeeId) {
		Employee emp = em.find(Employee.class, employeeId);
		model.addAttribute("emps", List.of(emp));
		return "employees.html";
	}
	
}
