package nl.nikhef.safaripark.vsp;

import java.awt.Component;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseEvent;
import java.util.Arrays;
import java.util.EventObject;

import javax.swing.AbstractCellEditor;
import javax.swing.JCheckBox;
import javax.swing.JTree;
import javax.swing.event.ChangeEvent;
import javax.swing.tree.TreeCellEditor;
import javax.swing.tree.TreePath;

public class CheckBoxNodeEditor extends AbstractCellEditor implements TreeCellEditor {

	CheckBoxNodeRenderer renderer = new CheckBoxNodeRenderer();

	ChangeEvent changeEvent = null;

	JTree tree;
	boolean firstTime = true;

	public CheckBoxNodeEditor(JTree tree) {
		this.tree = tree;
		
	}


	public boolean isCellEditable(EventObject event) {
		if (event instanceof MouseEvent) {
			MouseEvent mouseEvent = (MouseEvent) event;
			TreePath path = tree.getPathForLocation(mouseEvent.getX(),
					mouseEvent.getY());
			if (path != null) {
				Object node = path.getLastPathComponent();
				if ((node != null) && (node instanceof CheckableTreeNode)) {
					// CheckBoxNodeEditor treeNode = CheckBoxNodeEditor.class.cast(node);
					return true;
				}
			}
		}
		return false;
	}

	public Component getTreeCellEditorComponent(final JTree tree, Object value,
			boolean selected, boolean expanded, boolean leaf, int row) {

		Component editor = renderer.getTreeCellRendererComponent(tree, value,
				true, expanded, leaf, row, true);

		// editor always selected / focused
		ItemListener itemListener = new ItemListener() {
			public void itemStateChanged(ItemEvent itemEvent) {
				if (stopCellEditing()) {
					fireEditingStopped();
					tree.repaint();
				}
			}
		};
		if (editor instanceof JCheckBox && firstTime) {
//			JCheckBox cb = JCheckBox.class.cast(editor);
			
			((JCheckBox) editor).addItemListener(itemListener);
			firstTime = false;
		}

		return editor;
	}


	@Override
	public Object getCellEditorValue() {
		TristateCheckbox editor = renderer.getRenderer();
		return editor.getSelectionState();
	}
}