import objectdraw.*;
import java.awt.*;
import javax.swing.*;

/**
 * A general collection class to store Drawable Shapes.
 */
public class ShapeCollection {

  private static final int MAX_OBJECTS = 20;

  // Array of objects in collection
  private DrawableInterface[] shapes;

  // number of objects in collection
  private int numShapes;

  /*
   * Create a new, empty Collection
   */
  public ShapeCollection() {
    shapes = new DrawableInterface[MAX_OBJECTS];
    numShapes = 0;
  }

  /*
   * Add the shape to the collection.
   */
  public void add(DrawableInterface shape) {
    // only add if still room for more objects
    if (numShapes < shapes.length) {
      shapes[numShapes] = shape;
      numShapes++;
    }
  }

  /*
   * Add the shape to the beginning of the collection.
   */
  public void addFirst(DrawableInterface shape) {
    if (numShapes < shapes.length) {
      for (int i = numShapes; i > 0; i--) {
        shapes[i] = shapes[i - 1];
      }
      shapes[0] = shape;
      numShapes++;
    }
  }

  /*
   * Return the first shaping containing point, starting from the most
   * recently added shape.
   */
  public DrawableInterface selectedShape(Location point) {
    // Walk the array until we find the selected shape
    for (int selectIndex = numShapes - 1; selectIndex >= 0; selectIndex--) {
      if (shapes[selectIndex].contains(point)) {
        return shapes[selectIndex];
      }
    }

    return null;
  }

  public void remove(DrawableInterface shape) {
    int selectIndex = this.getIndexOf(shape);

    // if point is in one of the objects, delete it
    if (selectIndex != -1) {
      for (int i = selectIndex; i < numShapes - 1; i++) {
        shapes[i] = shapes[i + 1];
      }

      numShapes--;
      shapes[numShapes] = null;
    }
  }

  /*
   * Helper method to return the index of the given shape.
   */
  private int getIndexOf(DrawableInterface shape) {
    // Walk the array until we find the selected shape
    for (int selectIndex = numShapes - 1; selectIndex >= 0; selectIndex--) {
      if (shapes[selectIndex] == shape) {
        return selectIndex;
      }
    }

    return -1;
  }
}
