package inc.monsters.mias.backing;

import inc.monsters.mias.Util;
import inc.monsters.mias.data.Employee;

import java.util.Iterator;
import java.util.Map;
import java.util.logging.Logger;

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 {
	private static final Logger log = Logger.getLogger("inc.monsters.mias");
	private UIXTable table;
	private boolean showAsList = false;

	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 void deleteSelected(ActionEvent event) {
		Object oldRowKey = getTable().getRowKey(); // Remember the current row key of the table.
		
		Iterator<Object> selectedKeys = getTable().getSelectedRowKeys().iterator();
		Map<Integer, Employee> map = Util.getEmployeesMap();
		log.finest("Map of employees contains " + map.size() + "employees.");
		while(selectedKeys.hasNext()) {
			Object key = selectedKeys.next();
			log.finer("Selected key = " + key);
			getTable().setRowKey(key);
			Employee emp = (Employee) getTable().getRowData();
			log.finer("Removing kid: " + emp.getId() + ": " + emp.getFirstName() + " " + emp.getLastName() + ".");
			map.remove(emp.getId());
		}
		
		getTable().setSelectedRowKeys(null); // Reset the selection
		getTable().setRowKey(oldRowKey); // Reset the current row key to the remembered value.
	}
	
	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";
	}
}
