// File: ParcelsToSend.java
// Time-stamp: "2006-02-12 21:53:05 calvanese"
// Purpose: Written exam 8/2/2006 - BSc in Computer Science (8CFU)
//          solution part 1

class Node {
  String parcel;
  Node next;
}


public class ParcelsToSend {

  // representation of the objects
  private String country;
  private Node first, last;

  // pubblic methods

  public ParcelsToSend(String c) {
    country = c;
    first = null;
    last = null;
  }
  
  public String getCountry() {
    return country;
  }
  
  public void insertParcel(String parcel) {
    if (first == null) {
      last = new Node();
      first = last;
    } else {
      last.next = new Node();
      last = last.next;
    }
    last.parcel = parcel;
    last.next = null;
  }
  
  public String nextParcel() throws ParcelsException {
    if (first != null)
      return first.parcel;
    else
      throw new ParcelsException("Parcel sequence is empty.");
  }

  public String sendParcel() throws ParcelsException {
    if (first != null) {
      String res = first.parcel;
      first = first.next;
      return res;
    } else
      throw new ParcelsException("Parcel sequence  is empty.");
  }

  public int numParcels() {
    Node aux = first;
    int count = 0;
    while (aux != null) {
      count++;
      aux = aux.next;
    }
    return count;
  }
  
  public String parcel(int pos) throws ParcelsException {
    Node aux = first;
    if (pos >= 0 && pos < numParcels()) {
      while (pos > 0) {
        pos--;
        aux = aux.next;
      }
      return aux.parcel;
    }
    else
      throw new ParcelsException("Invalid parcel position.");
  }

  public int[] parcelsForAddress(String s) {
    int[] res = new int[numParcelsForAddress(s)];
    int pos = 0;
    Node aux = first;
    int count = 0;
    while (aux != null) {
      if (aux.parcel != null && aux.parcel.startsWith(s)) {
        res[pos] = count;
        pos++;
      }
      count++;
      aux = aux.next;
    }
    return res;
  }

  private int numParcelsForAddress(String s) {
    Node aux = first;
    int count = 0;
    while (aux != null) {
      if (aux.parcel != null && aux.parcel.startsWith(s))
        count++;
      aux = aux.next;
    }
    return count;
  }

}
