/* This class is a generic TreeElement which can represent any object, but not does need
   any special behavior. */

/* Copyright (C) 2001 by Peter Eastman

   This program is free software; you can redistribute it and/or modify it under the
   terms of the GNU General Public License as published by the Free Software
   Foundation; either version 2 of the License, or (at your option) any later version.

   This program is distributed in the hope that it will be useful, but WITHOUT ANY
   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
   PARTICULAR PURPOSE.  See the GNU General Public License for more details. */

package artofillusion.ui;

import artofillusion.*;
import artofillusion.animation.*;
import java.util.*;

public class MenuTreeElement extends GenericTreeElement
{
  boolean isMenu;
  boolean isRoot;
  
  public MenuTreeElement(MenuDescription desc,
      TreeList tree, TreeElement[] children)
  {
    super(desc.getPresentableString(), desc, null, tree, arrayToVector(children));
    isMenu = children != null;
    isRoot = false;
  }
  
  public void setAsRoot()
  {
    isRoot = true;
  }
  
  /** Read and set the label from desc. */
  public void rereadLabel()
  {
    setLabel(getItemDescription().getPresentableString());
  }

  public static Vector arrayToVector(Object[] arr) // TODO(MB) Remove
  {
    if (arr == null)
      return null;

    Vector result = new Vector();
    for(int i = 0; i < arr.length; ++i)
      result.add(arr[i]);

    return result;
  }

  public boolean acceptsChildren()
  {
    return isMenu;
  }
  
  /** Returns if this is a modifiable menu. */
  
  public boolean representsMenu()
  {
    return isMenu;
  }
  
  public MenuDescription getItemDescription()
  {
    return (MenuDescription)getObject();
  }

  public boolean canAcceptAsParent(TreeElement el)
  {
    if (el == null && !isRoot)
      return false;
    
    if (el != null && isRoot)
      return false;
    
    if (el == this)
      return false;
    
    return (el instanceof MenuTreeElement) &&
        ((MenuTreeElement)el).acceptsChildren();
  }

  /** Remove child element elm (tested by identity ==).
   */
  
  public void removeIdentChildElement(MenuTreeElement toremove)
  {
    TreeElement el = null;
    int pos;
    
    for (pos = 0; pos < children.size(); pos++)
      {
        el = (TreeElement) children.elementAt(pos);
        if (el == toremove)
          break;
      }
    if (pos == children.size())
      {
        for (int i = 0; i < children.size(); i++)
          ((MenuTreeElement) children.elementAt(i)).removeIdentChildElement(toremove);
        return;
      }
    el.parent = null;
    children.removeElementAt(pos);
  }
  
  /** Return if the element can be removed from the TreeList. */
  
  public boolean isDeletable()
  {
    return !isRoot;
  }


}