import java.awt.geom.Line2D;
import java.awt.geom.Path2D;
import java.awt.geom.Point2D;
import java.util.ArrayList;

/**
 * Polygon Tool
 * 
 * @author swansom1. Created Apr 11, 2008.
 */
public class Polygon implements Tools {

	private Path2D path;

	private Point2D initialPoint;

	private ArrayList<Point2D> points;

	/**
	 * creates the Polygon
	 * 
	 * @param x
	 * @param y
	 */
	public Polygon(int x, int y) {

		this.initialPoint = new Point2D.Double(x, y);
		this.points = new ArrayList<Point2D>();
		this.points.add(this.initialPoint);
		Line2D line = new Line2D.Double(x, y, x, y);
		this.path = new Path2D.Double(line);
	}

	/**
	 * draws the polygon
	 * 
	 * @param x
	 * @param y
	 * @return Polygon made from current mouse position
	 */
	public Path2D draw(int x, int y) {

		Point2D.Double p = new Point2D.Double(x, y);
		this.path.reset();
		if (p.distance(this.initialPoint) <= 10) {
			this.path.moveTo(this.initialPoint.getX(), this.initialPoint.getY());
			for (int i = 0; i < this.points.size(); i++) {
				this.path.lineTo(this.points.get(i).getX(), this.points.get(i).getY());
			}
			this.path.closePath();
			return this.path;
		}
		this.path.moveTo(this.initialPoint.getX(), this.initialPoint.getY());
		for (int i = 0; i < this.points.size(); i++) {
			this.path.lineTo(this.points.get(i).getX(), this.points.get(i).getY());
		}
		this.path.lineTo(x, y);
		this.points.add(p);
		this.points.remove(this.points.size() - 2);
		return this.path;
	}

	/**
	 * completes the polygon with a final line
	 * 
	 * @param x
	 * @param y
	 * @return The final Path2D of the polygon
	 */
	public Path2D finalPoint(int x, int y) {

		Point2D.Double p = new Point2D.Double(x, y);
		this.path.reset();
		if (p.distance(this.initialPoint) <= 10) {
			this.path.moveTo(this.initialPoint.getX(), this.initialPoint.getY());
			for (int i = 0; i < this.points.size() - 1; i++) {
				this.path.lineTo(this.points.get(i).getX(), this.points.get(i).getY());
			}
			this.path.closePath();
			return this.path;
		}
		this.path.moveTo(this.initialPoint.getX(), this.initialPoint.getY());
		for (int i = 0; i < this.points.size(); i++) {
			this.path.lineTo(this.points.get(i).getX(), this.points.get(i).getY());
		}
		this.path.lineTo(x, y);
		this.points.add(p);
		return this.path;
	}

	/**
	 * Checks if a new Polygon is ready to be made
	 * 
	 * @param j
	 * @param i
	 * 
	 * @return Should new polygon be made?
	 */
	public boolean checkState(int i, int j) {

		if (new Point2D.Double(i, j).distance(this.initialPoint) <= 10 && this.points.size() > 2) {
			return true;
		}
		return false;
	}

	/**
	 * completes the polygon if the cursor leaves the canvaspanel
	 * 
	 * @return The path, which will be closed off using last point added
	 */
	public Object exited() {

		this.path.closePath();
		return this.path;
	}

}
