package serwlety;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.persistence.TypedQuery;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.Department;
import model.Employee;

@WebServlet("/OdczytJpa2")
public class OdczytJpa2 extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	@PersistenceUnit(unitName="HR")
	private EntityManagerFactory emf;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/plain");
		response.setCharacterEncoding("utf-8");		
		PrintWriter out = response.getWriter();
		
		EntityManager em = null;
		try {
			out.println("emf = " + emf);
			em = emf.createEntityManager();
			out.println("em  = " + em);
			
			TypedQuery<Employee> namedQuery = em.createNamedQuery("Employee.findAll", Employee.class);
			
			List<Employee> employees = namedQuery.getResultList();
			out.println("Odczytano " + employees.size() + " pracowników:");
			for(Employee emp : employees) {
				Department dep = emp.getDepartment();
				String depName = dep == null ? "-" : dep.getDepartmentName();
				String city = dep == null || dep.getLocation() == null ? "-" : dep.getLocation().getCity();
				
				out.printf(" * %s %s %s %s %s\n",
						emp.getFirstName(),
						emp.getLastName(),
						emp.getSalary(),
						depName,
						city);
			}
			out.println("KONIEC");
		} finally {
			if(em != null)
				em.close();
		}
	}
}
