package inc.monsters.mias.backing;

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

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

import javax.faces.event.ActionEvent;

import org.apache.myfaces.trinidad.component.UIXTable;
import org.apache.myfaces.trinidad.component.core.nav.CoreCommandButton;
import org.apache.myfaces.trinidad.context.RequestContext;
import org.apache.myfaces.trinidad.event.SelectionEvent;

public class KidsTable {
	private static final Logger log = Logger.getLogger("inc.monsters.mias");
	private UIXTable table;
	private CoreCommandButton deleteButton;
	private boolean deleteEnabled = false;

	public UIXTable getTable() {
		return table;
	}

	public void setTable(UIXTable table) {
		this.table = table;
	}
	
	public CoreCommandButton getDeleteButton() {
		return deleteButton;
	}

	public void setDeleteButton(CoreCommandButton deleteButton) {
		this.deleteButton = deleteButton;
	}

	public boolean isDeleteEnabled() {
		return deleteEnabled;
	}

	public void setDeleteEnabled(boolean deleteEnabled) {
		this.deleteEnabled = deleteEnabled;
	}

	public void selectionChanged(SelectionEvent e) {
		log.fine("selectionChanged(): " + getTable().getSelectedRowKeys().size());
		boolean oldValue = isDeleteEnabled();
		setDeleteEnabled(getTable().getSelectedRowKeys().size() > 0);
		if(oldValue != isDeleteEnabled()) {
			RequestContext rc = RequestContext.getCurrentInstance();
		    rc.addPartialTarget(getDeleteButton());			
		}
	}
	
	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, Kid> map = Util.getKidsMap();
		log.finest("Map of kids contains " + map.size() + " kids.");
		int deleted = 0;
		while(selectedKeys.hasNext()) {
			Object key = selectedKeys.next();
			log.finer("Selected key = " + key);
			getTable().setRowKey(key);
			Kid kid = (Kid) getTable().getRowData();
			log.finer("Removing kid: " + kid.getId() + ": " + kid.getFirstName() + " " + kid.getLastName() + ".");
			map.remove(kid.getId());
			deleted++;
		}
		
		getTable().setSelectedRowKeys(null); // Reset the selection
		getTable().setRowKey(oldRowKey); // Reset the current row key to the remembered value.
		
		if(deleted > 0) {
			RequestContext rc = RequestContext.getCurrentInstance();
		    rc.addPartialTarget(getTable());
		}
	}
}
