/*
 * Licensed Materials - Property of Perforce Software, Inc. 
 * © Copyright Perforce Software, Inc. 2014, 2021 
 * © Copyright IBM Corp. 2009, 2014
 * © Copyright ILOG 1996, 2009
 * All Rights Reserved.
 *
 * Note to U.S. Government Users Restricted Rights:
 * The Software and Documentation were developed at private expense and
 * are "Commercial Items" as that term is defined at 48 CFR 2.101,
 * consisting of "Commercial Computer Software" and
 * "Commercial Computer Software Documentation", as such terms are
 * used in 48 CFR 12.212 or 48 CFR 227.7202-1 through 227.7202-4,
 * as applicable.
 */

import java.util.Enumeration;
import java.util.Vector;

import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeModel;

import ilog.views.sdm.model.IlvSDMNode;

public class TreeSDMNode implements IlvSDMNode {
  private TreeSDMNode parent;
  private TreeModel treeModel;
  private Object treeNode;
  private Vector<IlvSDMNode> children;

  public TreeSDMNode(TreeModel treeModel, TreeSDMNode parent, Object treeNode) {
    this.parent = parent;
    this.treeModel = treeModel;
    this.treeNode = treeNode;

    createChildren();
  }

  Override
  public String getTag() {
    return "treenode";
  }

  Override
  public String getID() {
    return String.valueOf(hashCode());
  }

  Override
  public Enumeration<?> getChildren() {
    return children.elements();
  }

  Override
  public IlvSDMNode getParent() {
    return parent;
  }

  Override
  public Object getProperty(String property) {
    if (treeNode instanceof DefaultMutableTreeNode) {
      if (property.equals("userObject")) {
        return ((DefaultMutableTreeNode) treeNode).getUserObject();
      }
      if (property.equals("CSSclass") && ((DefaultMutableTreeNode) treeNode).getParent() != null) {
        return ((DefaultMutableTreeNode) ((DefaultMutableTreeNode) treeNode).getParent()).getUserObject();
      }
    }
    return null;
  }

  Override
  public String[] getPropertyNames() {
    if (treeNode instanceof DefaultMutableTreeNode)
      return new String[] { "userObject", "CSSclass" };
    else
      return new String[0];
  }

  // Private methods.

  private void createChildren() {
    children = new Vector<IlvSDMNode>();

    int count = treeModel.getChildCount(treeNode);
    for (int i = 0; i < count; i++) {
      Object childTreeNode = treeModel.getChild(treeNode, i);

      TreeSDMNode childSDMNode = new TreeSDMNode(treeModel, this, childTreeNode);
      children.addElement(childSDMNode);

      TreeSDMLink childSDMLink = new TreeSDMLink(this, childSDMNode);
      children.addElement(childSDMLink);
    }
  }
}