package inc.monsters.mias.backing;

import inc.monsters.mias.data.Employee;
import inc.monsters.mias.data.facade.EmployeeService;

import java.util.List;
import java.util.logging.Logger;

import javax.ejb.EJB;
import javax.el.ELResolver;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;

import org.apache.myfaces.trinidad.component.UIXTable;
import org.apache.myfaces.trinidad.context.RequestContext;

public class EmployeesTable {
	@EJB
	private EmployeeService service;
	
	private static final Logger log = Logger.getLogger("inc.monsters.mias");
	private UIXTable table;
	private boolean showAsList = false;
	private List<Employee> empList;

	public UIXTable getTable() {
		return table;
	}

	public void setTable(UIXTable table) {
		this.table = table;
	}
	
	public boolean isShowAsList() {
		return showAsList;
	}

	public void setShowAsList(boolean showAsList) {
		this.showAsList = showAsList;
	}
	
	public List<Employee> getEmployees() {
		if (null == empList) {
			empList = service.getEmployees();
			log.fine("Number of Employees: " + empList.size());
		}
		return empList;
	}
	
	public void saveSelected(ActionEvent event) {
	    RequestContext requestContext = RequestContext.getCurrentInstance();
	    Employee emp = (Employee)requestContext.getPageFlowScope().get("selectedEmployee");
	    service.updateEmployee(emp);
	}

	public String edit() {
	    FacesContext context = FacesContext.getCurrentInstance();
	    ELResolver elr = context.getApplication().getELResolver();
	    Employee employee = (Employee) elr.getValue(context.getELContext(), null, "emp");
	    if (employee == null) {
	    	return "";
	    }
	   
	    RequestContext requestContext = RequestContext.getCurrentInstance();
	    requestContext.getPageFlowScope().put("selectedEmployee", employee);

	    return "edit";
	}
}
