// File: PhotoGalleryArray.java
// Time-stamp: "2005-01-24 09:37:42 calvanese"
// Purpose: PhotoGallery: solution part 1 - using dynamic arrays

public class PhotoGalleryArray {

  // representation of the objects
  private static final int DIM = 10; // initial array dimension

  private String url;
  private int numPhotos;  // number of photos currently in the PhotoGallery
  private String[] photoList;


  // pubblic methods

  public PhotoGalleryArray(String u) {
    photoList = new String[DIM];   // initially all elements are null
    numPhotos = 0;
    url = u;
  }
  
  public int numPhoto() {
    return numPhotos;
  }
  
  public void add(String photo) {
    if (photo != null) {
      if (numPhotos == photoList.length) {
        String[] aux = new String[photoList.length * 2];
        for(int i = 0; i < numPhotos; i++) {
          aux[i] = photoList[i];
        }
        photoList = aux;
      }

      // add new photo
      int i = 0;
      while (i < photoList.length) { // we will always find an empty position
        if (photoList[i] == null) {
          photoList[i] = photo;
          numPhotos++;
          return;
        } else
          i++;
      }
    }
  }
  
  public void remove(String photo) {
    if (photo != null) {
      int i = 0;
      boolean found = false;
      while ((i < numPhotos) && !found)
        if (photoList[i].equals(photo)) {
          photoList[i] = null;
          numPhotos--;
          found = true;
        } else
          i++;

      if (found && numPhotos < photoList.length/4) {
        int newDim = (DIM > numPhotos * 2)? DIM : numPhotos * 2;
        photoList = compactPhotoList(newDim);
      }
    }
  }

  public boolean present(String photo) {
    for (int i = 0; i < photoList.length; i++)
      if (photoList[i] != null && photoList[i].equals(photo))
        return true;
    return false;
  }

  public String[] returnAllPhotos() {
    return compactPhotoList(numPhotos);
  }

  public void removeAll() {
    photoList = new String[DIM];
  }

  // auxiliary methods

  private String[] compactPhotoList(int newDim) {
    String[] res = new String[newDim];
    int pos = 0;
    for (int i = 0; i < photoList.length; i++)
      if (photoList[i] != null) {
        res[pos] = photoList[i];
        pos++;
      }
    return res;
  }

}
