package inc.monsters.mias.backing;

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

import java.util.List;

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;
import org.springframework.transaction.annotation.Transactional;

public class EmployeesTable {
	private EmployeeService employeeService;
	
	private UIXTable table;
	private boolean showAsList = false;

	public EmployeeService getEmployeeService() {
		return employeeService;
	}

	public void setEmployeeService(EmployeeService employeeService) {
		this.employeeService = employeeService;
	}

	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;
	}
	
	@Transactional(readOnly = true)
	public List<Employee> getEmployees() {
		List<Employee> list = employeeService.getEmployees();
		return list;
	}
	
	@Transactional
	public void saveSelected(ActionEvent event) {
	    RequestContext requestContext = RequestContext.getCurrentInstance();
	    Employee emp = (Employee)requestContext.getPageFlowScope().get("selectedEmployee");
	    employeeService.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";
	}
}
