package configuration;
import java.util.Vector;
import java.lang.System;

/**
 * Represents the attributes of a dependence.
 * It implements the <b>ComponentConfigurator</b> interface.
 * @author  Fabio Kon
 * @version 0.2
 * @see     DependencySpecification
*/
public class DependencyAttributes {

  // Helper class      
  public static class NameValue {
    public String name_;
    public Object value_;

    NameValue (String name, Object value)
    {
      name_  = name;  // this is OK because Strings are immutable
      value_ = value; // important: it copies the reference, not the value.
    }
  }
  
  protected Vector attributes_;

  /**
   * Creates a holder for dependency attributes.
   */
  public DependencyAttributes ()
  {
    attributes_ = new Vector (4, 8);
  }
  
 /**
  * Defines a new attribute or changes the value of an existing attribute.
  * Note that the value is not copied, it stores a reference to it.
  *
  * @param  name  the name of the attribute.
  * @param  value the value of the attribute.
  */
  public void setAttribute (String name, Object value)
  {
    NameValue nv = new NameValue (name, value);
    int i = indexOf (name);
    if (i > 0)
      attributes_.removeElementAt (i);

    attributes_.addElement (nv);
  }

 /**
  * Removes an attribute
  *
  * @param  name  the name of the attribute.
  */
  public void removeAttribute (String name) throws NotFound
  {
    int i = indexOf (name);
    if (i == -1)
      throw new NotFound ();
    else
      attributes_.removeElementAt (i);
  }

 /**
  * Accessor to the vector of attributes.
  *
  * @return a Vector containing NameValue objects corresponding to the attributes.
  * @see DependencyAttributes.NameValue
  */
  public Vector getAttributes ()
  {
    return attributes_;
  }

 /**
  * Accessor to the value of an attribute.
  *
  * @param attributeName the name of the attribute
  * @return an Object containing the value of the given attribute.
  * @see DependencyAttributes.NameValue
  */
  public Object getValue (String attributeName) throws NotFound
  {
    int i = indexOf (attributeName);
    if (i == -1)
      throw new NotFound ();
    else
      return ((NameValue)(attributes_.elementAt (i))).value_;
  }


  //////////////////////////////////////////////////////////////////////
  // Returns the index of the first attribute with the name provided.
  // Returns -1 if such element is not found.
  //////////////////////////////////////////////////////////////////////
  private int indexOf (String attributeName)
  {
    int i, size = attributes_.size();
    
    for (i = 0; i < size; i++)
      if(attributeName.equals(((NameValue)attributes_.elementAt(i)).name_))
	return i;
    
    return -1; // element not found.
  }
  
};


