/*
 * PhoneBook.java      Authors: Koffman and Wolz
 * Represents a telephone directory using an ArrayList.
 */
import java.util.ArrayList;

public class PhoneBook {
  // Data fields
  private ArrayList directory;
  private static int PAGE_SIZE = 5;  // friends on each page

  // Methods
  // postcondition: directory references an empty vector
  public PhoneBook() {
    directory = new ArrayList();
  }

  // postcondition: Adds its argument to the directory.
  public void addFriend(Friend aFriend) {
    directory.add(aFriend);
  }

  // postcondition: Returns the friend selected by its argument.
  public Friend getFriend(int index) {
    if (inDirectory(index))
      return (Friend) directory.get(index);
    else
      return null;
  }

  // postcondition: Returns the number of the friend whose
  //   name is referenced by its argument.
  public String getNumber(String friendName) {
    int index = findFriend(friendName);
    if (index >= 0)
      return ((Friend) directory.get(index)).getPhone();
    else
      return null;
  }

  // postcondition: Returns the index of the friend whose
  //   name is referenced by its argument.
  //   Returns -1 if not found.
  public int findFriend(String friendName) {
    for (int index = 0; index < directory.size(); index++) {
      if (((Friend) directory.get(index)).getName().equals(friendName))
        return index;
    }

    // friendName not found.
    return -1;
  }

  // postcondition: Returns true if its argument is in range.
  public boolean inDirectory(int index) {
    return index >= 0 && index < directory.size();
  }

  // postcondition: Returns a String representing the telephone
  //   directory. The page number is inserted at the beginning
  //   of each new page.
  public String toString() {
    String result = "";
    for (int index = 0; index < directory.size(); index++) {
      if (index % PAGE_SIZE == 0)
        result = result + "\npage: " + (1 + index / PAGE_SIZE) + "\n";
      result = result + directory.get(index) + "\n";
    }
    return result;
  }

  // postcondition: Returns the number of friends in the directory.
  //   Added for compatibility with the array implementation.
  public int getNumFriends() {
    return directory.size();
  }

  // postcondition: Returns the number of pages in the directory.
  //   Added for compatibility with the array implementation.
  public int getNumPages() {
    return 1 + directory.size() / PAGE_SIZE;
  }

}

