// File: Wardrobe2.java
// Time-stamp: "2005-01-09 18:24:37 calvanese"
// Scopo: Wardrobe: solution part 1

/*
  Alternative solution that makes use of an auxiliary class Hook to represent a
  hook.  See the comment in the other solution for a motivation for this
  choice.
*/

class Hook {
  boolean empty;
  String item;
}

public class Wardrobe2 {

  // representation of the objects
  private Hook[] hooks;
  
  // pubblic methods

  public Wardrobe2(int n) {
    hooks = new Hook[n];
    for (int i = 0; i < hooks.length; i++) {
      hooks[i] = new Hook();
      hooks[i].empty = true;
      hooks[i].item = null;
    }
  }

  public int getNumHooks() {
    return hooks.length;
  }

  public int assignHook(String c) {
    for (int i = 0; i < hooks.length; i++)
      if (hooks[i].empty) {
        hooks[i].empty = false;
        hooks[i].item = c;
        return i;
      }
    throw new RuntimeException("No empty hook");
  }

  public void emptyHook(int n) {
    if (n >= 0 && n < hooks.length) {
      hooks[n].empty = true;
      hooks[n].item = null;
    } else
      throw new RuntimeException("Hook number out of range");
  }

  public String getItem(int n) {
    if (n >= 0 && n < hooks.length)
      return hooks[n].item;
    else
      throw new RuntimeException("Hook number out of range");
  }

  public int searchItem(String c) {
    for (int i = 0; i < hooks.length; i++)
      if (hooks[i].item != null && hooks[i].item.equals(c)) 
        return i;
    return -1;
  }

  public int getNumOccupiedHooks() {
    int count = 0;
    for (int i = 0; i < hooks.length; i++) 
      if (!hooks[i].empty) count++;
    return count;
  }

  public void addHooks(int n) {
    if (n <= 0)
      throw new RuntimeException("Number of hooks to add must be positive");

    Hook[] newHooks = new Hook[hooks.length+n];
    for (int i = 0; i < hooks.length; i++)
      newHooks[i] = hooks[i];
    for (int i = hooks.length; i < newHooks.length; i++) {
      newHooks[i] = new Hook();
      newHooks[i].empty = true;
      newHooks[i].item = null;
    }
    hooks = newHooks;
  }

  public void reorderWardrobe() {
    int firstEmpty = -1;  // index of the first empty hook
    for (int i = 0; i < hooks.length; i++) {
      if (hooks[i].empty && firstEmpty == -1)
        firstEmpty = i;
      if (!hooks[i].empty && firstEmpty != -1) {
        hooks[firstEmpty].empty = false;
        hooks[firstEmpty].item = hooks[i].item;
        hooks[i].empty = true;
        firstEmpty++;
      }
    }
  }

}
