package adecWatt.model;

import java.util.Collections;
import java.util.Comparator;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.MutableTreeNode;
import javax.swing.tree.TreeNode;

@SuppressWarnings ("serial") public class UnitNode<E extends Embedded<?,?,?,?,?>> extends DefaultMutableTreeNode {
    // ========================================
    public UnitNode (Unit<E> unit) {
	super (unit);
    }

    @SuppressWarnings ("unchecked")
    public Unit<E> getUnit () {
	return (Unit<E>) getUserObject ();
    }

    // ========================================
    @SuppressWarnings("unchecked")
    public void insert (MutableTreeNode newChild, int childIndex) {
	if (children == null) {
	    super.insert (newChild, childIndex);
	    return;
	}
	int index = Collections.binarySearch (children, newChild, nodeComparator);
	if (index < 0)
	    super.insert (newChild, -index-1);
    }
    protected Comparator<TreeNode> nodeComparator =
	new Comparator<TreeNode> () {
	@Override public int compare (TreeNode o1, TreeNode o2) {
	    int result = o1.toString ().compareToIgnoreCase (o2.toString());
	    if (result != 0)
		return result;
	    // XXX
	    return ((UnitNode<?>) o1).getUnit ().getId ().compareToIgnoreCase (((UnitNode<?>) o2).getUnit ().getId ().toString());
	}
	@Override
	public boolean equals (Object obj)    {
	    return false;
	}
	@Override public int hashCode() {
	    int hash = 7;
	    return hash;
	}
    };
    // ========================================
    public String toString () {
	return getUnit ().getLocalName ();
    }
    // ========================================
}
