import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseEvent;
import java.awt.geom.Ellipse2D;

/**
 * Draws an oval from the point of initial click to the point where the mouse is
 * released.
 * 
 * @author Joel Carlson and Ty Strayer. Created Apr 11, 2008.
 */
public class OvalTool extends Tool {
	private int x1, y1, width, height, topLeftX, topLeftY, dimension;

	private Color outlineColor;

	private Color fillColor;

	private Ellipse2D.Double oval = new Ellipse2D.Double(0, 0, 0, 0);

	/**
	 * Creates an Oval tool with access to the given DrawableArea.
	 * 
	 * @param drawArea
	 *            The DrawableArea the tool has access to.
	 */
	public OvalTool(DrawableArea drawArea) {
		this.drawArea = drawArea;
	}

	@Override
	public void mouseDragged(MouseEvent e) {
		this.dimension = Math.min(this.width, this.height);
		this.width = e.isShiftDown() ? this.dimension : Math.abs(this.x1
				- e.getX());
		this.height = e.isShiftDown() ? this.dimension : Math.abs(this.y1
				- e.getY());

		this.topLeftX = this.x1 < e.getX() ? this.x1 : this.x1 > e.getX()
				&& e.isShiftDown() ? this.x1 - this.dimension : this.x1
				- this.width;

		this.topLeftY = this.y1 < e.getY() ? this.y1 : this.y1 > e.getY()
				&& e.isShiftDown() ? this.y1 - this.dimension : this.y1
				- this.height;

		this.oval.x = this.topLeftX;
		this.oval.y = this.topLeftY;
		this.oval.width = this.width;
		this.oval.height = this.height;

		this.width = Math.abs(this.x1 - e.getX());
		this.height = Math.abs(this.y1 - e.getY());

		this.getParent().repaint();

	}

	@Override
	public void mousePressed(MouseEvent e) {
		this.x1 = e.getX();
		this.y1 = e.getY();
		this.oval.x = this.x1;
		this.oval.y = this.y1;
		this.outlineColor = this.drawArea.getOutlineColor();
		this.fillColor = this.drawArea.getFillColor();
		this.getParent().repaint();
	}

	@Override
	public void mouseReleased(MouseEvent e) {
		this.getParent().repaint();
		this.drawArea.disableLastTool();
		this.drawArea.addTool(new OvalTool(this.drawArea));
	}

	@Override
	public void drawTool(Graphics g) {
		super.drawTool(g);
		Graphics2D g2 = (Graphics2D) g;
		if (this.fillColor != null) {
			g2.setColor(this.fillColor);
			g2.fill(this.oval);
		}
		g2.setColor(this.outlineColor);
		g2.draw(this.oval);
	}

}