// File: Counter.java
// Time-stamp: "2005-01-22 09:57:55 calvanese"
// Purpose: Counter: solution part 2

public class Counter {

  private Request[] queue;
  private int       queueSize;
  private int       progressiveNumber;


  public Counter(int capacity) {
    queue = new Request[capacity] ;
    progressiveNumber = 0;
    queueSize = 0;
  }


  public int addRequest(String name) {
    if (queueSize == queue.length)
      return -1;
    else {
      // add new request
      queue[queueSize] = new Request(name, progressiveNumber);
      queueSize++;
      progressiveNumber++;
      return progressiveNumber - 1;
    }
  }


  public Request handleRequest() {
    if (queueSize == 0) {
      return null;
    } else {
      Request p = queue[0];

      // shift array, eliminating queue[0]
      for (int i = 0; i < queueSize - 1; i++) {
        queue[i] = queue[i + 1];
      }
      queue[queueSize - 1] = null;
      queueSize--;

      return p;
    }
  }


  public void giveUp(int number) {
    // find element queue[k] having queue[k].getNumber() == number
    int k = 0;
    while (k < queueSize && queue[k].getNumber() != number) {
      k++;
    }

    if (k < queueSize && queue[k].getNumber() == number) {
      // shift all elements starting from the k-th element one position down
      for(int i = k; i < queueSize - 1; i++) {
        queue[i] = queue[i + 1];
      }
      queue[queueSize - 1] = null;
      queueSize--;

    } // else do nothing
  }


  public int waitingTime(int number) {
    // find element queue[k] having queue[k].number == number
    int k = 0;
    while (k < queueSize && queue[k].getNumber() != number)
      k++;

    if (k < queueSize && queue[k].getNumber() == number)
      return k;
    else
      return -1;
  }


  public String toString() {
    String ris = "";
    for (int i = 0; i < queueSize; i++)
      ris = ris + queue[i] + "\n";
    return ris;
  }

}
