package profesorsi.webapp;

import java.util.Collection;
import java.util.List;

import javax.persistence.EntityManager;

import org.zkoss.bind.annotation.BindingParam;
import org.zkoss.bind.annotation.Command;
import org.zkoss.bind.annotation.NotifyChange;
import org.zkoss.zkplus.jpa.JpaUtil;

import persistence.Department;
import persistence.Employee;

public class EmployeesVM {

	private Employee currentEmployee = null;
	
	public Employee getCurrentEmployee() {
		return currentEmployee;
	}
	
	public Collection<Department>
	getDepartments() {
		System.out.println("getDepartments()");
		EntityManager em = JpaUtil.getEntityManager();
		
		List<Department> departments = em.createQuery("SELECT d FROM Department d",
				Department.class).getResultList();
		for (Department d : departments) {
			d.getEmployees().size();
		}
		
		return departments;
	}
	
	public Collection<Employee>
		getEmployees() {
		System.out.println("getEmployees()");
		EntityManager em = JpaUtil.getEntityManager();
		
		return em.createQuery("SELECT e FROM Employee e",
				Employee.class).getResultList();
	}
	
	@NotifyChange("currentEmployee")
	@Command
	public void edit(@BindingParam("employee") Employee employee) {
		this.currentEmployee = employee;
	}
	
	@NotifyChange("employees")
	@Command
	public void delete(@BindingParam("employee") Employee employee) {
		EntityManager em = JpaUtil.getEntityManager();
		em.remove(em.merge(employee));
	}
	

	
	@NotifyChange("currentEmployee")
	@Command
	public void newEmployee() {
		this.currentEmployee = new Employee();
	}
	
	@NotifyChange({"currentEmployee", "employees", "departments"})
	@Command
	public void save() {
		EntityManager em = JpaUtil.getEntityManager();
		em.merge(this.currentEmployee);
		this.currentEmployee = null;
	}
	
	@NotifyChange("currentEmployee")
	@Command
	public void cancel() {
		this.currentEmployee = null;
	}
}

@@ -546,19 +546,17 @@
 artment%3E
-%0D%0A%09
+ 
 getDepar
@@ -697,16 +697,22 @@
 ments = 
+%0D%0A%09%09%09%09
 em.creat
@@ -747,22 +747,17 @@
 ment d%22,
-%0D%0A%09%09%09%09
+ 
 Departme
@@ -761,24 +761,28 @@
 tment.class)
+%0D%0A%09%09
 .getResultLi
@@ -788,16 +788,334 @@
 ist();%0D%0A
+%09%09%0D%0A%09%09// force initialization of the getEmployees lazy loaded collection%0D%0A%09%09// since the Departments become detached just after the end of the%0D%0A%09%09// request, but we will add the currentEmployee to the collection%0D%0A%09%09// of one of the detached Departments in the combo (which would throw%0D%0A%09%09// a lazy loading exception)%0D%0A
 %09%09for (D
@@ -1812,13 +1812,8 @@
 %0D%0A%09%0D
-%0A%0D%0A%09%0D
 %0A%09@N
@@ -1923,35 +1923,191 @@
 mployee();%0D%0A%09%7D%0D%0A
-
 %09%0D%0A
+%09// We add here departments in order to, the department of the %0D%0A%09// currentEmployee always match one of the departments %0D%0A%09// in the departments combobox%0D%0A
 %09@NotifyChange(%7B

Add code comments