/*This code was generated using the UMPLE modeling language!*/

package airlineMajorExample;

import java.util.HashMap;
import java.util.Set;

public class AirlineMajorExampleRegistry {

  // Singleton instance.
  private static AirlineMajorExampleRegistry theInstance;

  // Hash table for the objects.
  HashMap<Integer, Object> systemHash = new HashMap<Integer, Object>();

  // Singleton key.
  int highestKey = 0;

  /**
   * Dummy constructor
   */
  private AirlineMajorExampleRegistry() {
  }

  /**
   * Returns the only instance of the registry.
   * 
   * @return
   */
  public static AirlineMajorExampleRegistry getInstance() {
    if (theInstance == null)
      theInstance = new AirlineMajorExampleRegistry();
    return theInstance;
  }

  /**
   * Returns the object in the registry with a given key.
   * 
   * @param key
   * @return
   */
  public Object getValue(int key) {
    return systemHash.get(new Integer(key));
  }

  /**
   * Returns the key of a given object.
   * 
   * @param obj
   * @return
   */
  public Integer getKey(Object obj) {
    for (Integer entryKey : systemHash.keySet()) {
      if (systemHash.get(entryKey).equals(obj)) {
        return entryKey;
      }
    }
    return new Integer(-1);
  }

  /**
   * Inserts an object into the registry.
   * 
   * @param obj
   * @return returns the key given to that object.
   */
  public Integer add(Object obj) {
    if (!systemHash.containsValue(obj)) {
      Integer returnKey = getNextKey();
      systemHash.put(returnKey, obj);
      return returnKey;
    } else {
      //TODO: This needs to be reworked. Looking through the whole key set 
      // to return the key assigned to this object is unacceptable.
      Set<Integer> keys = systemHash.keySet();
      for (Integer key : keys) {
        if (systemHash.get(key).equals(obj))
          return key;
      }
      return -1;
    }
  }

  /**
   * Removes an object with the given key.
   * 
   * @param key
   */
  public void removeObj(int key) {
    if (key != -1 && systemHash.containsKey(new Integer(key)))
      systemHash.remove(new Integer(key));
  }

  /**
   * Gets the next key to use in the hash table.
   * 
   * @return
   */
  private Integer getNextKey() {
    return new Integer(highestKey++);
  }
}
