package przyklady;

import hr.model.Employee;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
import jakarta.persistence.TypedQuery;

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

public class P5_Parametry {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        try(EntityManagerFactory emf = Persistence.createEntityManagerFactory("hr");
            EntityManager em = emf.createEntityManager()) {

            System.out.print("Podaj dwie liczby, zakres pensji: ");
            BigDecimal min = scanner.nextBigDecimal();
            BigDecimal maks = scanner.nextBigDecimal();
            scanner.nextLine();

            // JPQL = Jakarta Persistence Query Language
            // Jak SQL, ale na poziomie obiektów, z pewnymi różnicami i ograniczeniami.
            // Parametry wpisuje się za pomocą :nazwa
            final String select1 = "SELECT e FROM Employee e WHERE e.salary BETWEEN :min AND :max ORDER BY e.salary DESC";
            TypedQuery<Employee> query1 = em.createQuery(select1, Employee.class);
            query1.setParameter("min", min);
            query1.setParameter("max", maks);
            List<Employee> employees = query1.getResultList();

            System.out.println("Odczytano " + employees.size() + " rekordów.");
            for(Employee employee : employees) {
                System.out.println(employee.getFirstName() + " " + employee.getLastName()
                        + " (" + employee.getJob().getJobTitle() + "): " + employee.getSalary());
            }

            System.out.print("Podaj miasto: ");
            String city = scanner.nextLine();
            final String select2 = "SELECT e FROM Employee e WHERE e.department.location.city = :city";
            TypedQuery<Employee> query2 = em.createQuery(select2, Employee.class);
            query2.setParameter("city", city);
            query2.getResultStream()
                    .map(emp -> emp.getFirstName() + " " + emp.getLastName())
                    .forEach(System.out::println);
        }
    }
}
