package com.positive.charts.entity;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.graphics.Region;
/**
* A standard implementation of the {@link EntityCollection} interface.
*/
public class StandardEntityCollection implements EntityCollection {
/** Storage for the entities. */
private final List entities;
/**
* Constructs a new entity collection (initially empty).
*/
public StandardEntityCollection() {
this.entities = new java.util.ArrayList();
}
/**
* Adds an entity to the collection.
*
* @param entity
* the entity (<code>null</code> not permitted).
*/
public void add(final ChartEntity entity) {
if (entity == null) {
throw new IllegalArgumentException("Null 'entity' argument.");
}
this.entities.add(entity);
}
/**
* Adds all the entities from the specified collection.
*
* @param collection
* the collection of entities.
*/
public void addAll(final EntityCollection collection) {
this.entities.addAll(collection.getEntities());
}
/**
* Clears the entities.
*/
public void clear() {
this.entities.clear();
}
/**
* Returns the entities in an unmodifiable collection.
*
* @return The entities.
*/
public Collection getEntities() {
return Collections.unmodifiableCollection(this.entities);
}
/**
* Returns the last entity in the list with an area that encloses the
* specified coordinates, or <code>null</code> if there is no such entity.
*
* @param x
* the x coordinate.
* @param y
* the y coordinate.
*
* @return The entity (possibly <code>null</code>).
*/
public ChartEntity getEntity(final double x, final double y) {
final int entityCount = this.entities.size();
for (int i = entityCount - 1; i >= 0; i--) {
final ChartEntity entity = (ChartEntity) this.entities.get(i);
final Region area = entity.getArea();
if (area != null) {
if (area.contains((int) x, (int) y)) {
return entity;
}
}
final Rectangle rectangle = entity.getRectangle();
if (rectangle != null) {
if (rectangle.contains((int) x, (int) y)) {
return entity;
}
}
}
return null;
}
/**
* Returns a chart entity from the collection.
*
* @param index
* the entity index.
*
* @return The entity.
*/
public ChartEntity getEntity(final int index) {
return (ChartEntity) this.entities.get(index);
}
/**
* Returns the number of entities in the collection.
*
* @return The entity count.
*/
public int getEntityCount() {
return this.entities.size();
}
/**
* Returns an iterator for the entities in the collection.
*
* @return An iterator.
*/
public Iterator iterator() {
return this.entities.iterator();
}
}