/*
 * Created on Feb 20, 2004
 *
 */
package actor;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author Robbins
 *
 */
public class BehaviorList implements PropertyChangeListener
{
  private List behaviors = new ArrayList();
  private List listeners = new ArrayList();
  
  public void addListener(BehaviorListListener bL)
  {
    listeners.add(bL);
  }
  
  public void removeListener(BehaviorListListener bL)
  {
    listeners.remove(bL);
  }
  
  public void removeAllListener()
  {
    listeners.clear();
  }
  
  public synchronized void notifyListeners(BehaviorListChangedEvent bce) 
  {
    for(Iterator i = listeners.iterator(); i.hasNext();)
    {
      ((BehaviorListListener)i.next()).onBehaviorListChange(bce);
    }
  }
  
  /**
   * @param arg0
   * @return
   */
  public boolean add(Behavior b)
  {
    b.addPropertyChangeListener(this);
    notifyListeners(
      new BehaviorListChangedEvent(
        this,
        (AbstractBehavior) b,
        BehaviorListChangedEvent.ADDED));
    return behaviors.add(b);
  }

  /**
   * 
   */
  public void clear()
  {
    notifyListeners(
      new BehaviorListChangedEvent(this, null, BehaviorListChangedEvent.LIST_CLEARED));
    behaviors.clear();
  }

  /**
   * @param arg0
   * @return
   */
  public boolean contains(Behavior b)
  {
    return behaviors.contains(b);
  }

  /**
   * @return
   */
  public boolean isEmpty()
  {
    return behaviors.isEmpty();
  }

  /**
   * @return
   */
  public Iterator iterator()
  {
    return behaviors.iterator();
  }

  /**
   * @param arg0
   * @return
   */
  public boolean remove(Behavior b)
  {
    notifyListeners(
      new BehaviorListChangedEvent(
        this,
        (AbstractBehavior) b,
        BehaviorListChangedEvent.REMOVED));
    return behaviors.remove(b);
  }

  /**
   * @return
   */
  public int size()
  {
    return behaviors.size();
  }

  /**
   * @return
   */
  public AbstractBehavior[] toArray()
  {
    return (AbstractBehavior[])behaviors.toArray();
  }

  /**
   * @param arg0
   * @return
   */
  public AbstractBehavior[] toArray(AbstractBehavior[] arg0)
  {
    return (AbstractBehavior[]) behaviors.toArray(arg0);
  }

  /* (non-Javadoc)
   * @see java.lang.Object#toString()
   */
  public String toString()
  {
    return behaviors.toString();
  }

  /**
   * @param arg0
   * @return
   */
  public AbstractBehavior get(int arg0)
  {
    return (AbstractBehavior) behaviors.get(arg0);
  }

  public void propertyChange(PropertyChangeEvent pce)
  {
    this.notifyListeners(
      new BehaviorListChangedEvent(
        this,
        (AbstractBehavior) pce.getSource(),
        BehaviorListChangedEvent.CHANGED));
  }

}