package org.mbari.vdm.knowledgebase;


//~--- JDK imports ------------------------------------------------------------

import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.MutableTreeNode;
import javax.swing.tree.TreeNode;

/**
* @author brian
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class SortedTreeNode extends DefaultMutableTreeNode {

  //~--- constructors -------------------------------------------------------

  /**
   *
   */
  public SortedTreeNode() {
      super();
  }

  /**
   * @param userObject
   */
  public SortedTreeNode(Object userObject) {
      super(userObject);
  }

  /**
   * @param userObject
   * @param allowsChildren
   */
  public SortedTreeNode(Object userObject, boolean allowsChildren) {
      super(userObject, allowsChildren);
  }

  //~--- methods ------------------------------------------------------------

  /**
   * <p><!-- Method description --></p>
   *
   *
   * @param node
   */
  public void add(MutableTreeNode node) {
      if (node instanceof DefaultMutableTreeNode) {
          DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode) node;
          Object obj = treeNode.getUserObject();
          boolean added = false;

          if (obj instanceof Comparable) {
              Comparable thisComp = (Comparable) obj;

              for (int i = 0; i < getChildCount(); i++) {
                  TreeNode thatNode = getChildAt(i);

                  if (thatNode instanceof DefaultMutableTreeNode) {
                      Object thatObj =
                          ((DefaultMutableTreeNode) thatNode)
                              .getUserObject();

                      if (thatObj instanceof Comparable) {
                          int c = thisComp.compareTo((Comparable) thatObj);

                          if (c == 0) {
                              super.add(node);

                              added = true;

                              break;
                          } else if (c < 0) {
                              super.insert(node, i);

                              added = true;

                              break;
                          }
                      }
                  }
              }
          }

          if (!added) {
              super.add(node);
          }
      }
  }
}
