package serwlety;

import java.io.IOException;
import java.math.BigDecimal;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
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.Employee;

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

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		long idPracownika = -1;
		try {
			idPracownika = Long.parseLong(request.getParameter("id"));
		} catch (NumberFormatException e) {
			// zostawiam -1
		}
		
		if(idPracownika >= 0) {
			zmienPracownika(idPracownika);
		}
		
		response.sendRedirect("faces/pracownicy-tabela.xhtml");
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

	private void zmienPracownika(long idPracownika) {
		EntityManager em = null;
		try {
			em = emf.createEntityManager();
			em.getTransaction().begin();
			Employee emp = em.find(Employee.class, idPracownika);
			if(emp != null) {
				BigDecimal salary = emp.getSalary();
				salary = salary.add(BigDecimal.ONE);
				emp.setSalary(salary);
				
				em.persist(emp);
				System.out.println("persist");
				em.getTransaction().commit();
				System.out.println("commit id=" + idPracownika);
			} else {
				System.out.println("employee = null, id=" + idPracownika);
			}
		} finally {
			if(em != null)
				em.close();
		}
	}
}
