/*
 * File: PickAColor.java
 * -----------------------
 * Click on a colored square to choose a color.
 * Click on a blank square to fill it in with the chosen color.
 */

import java.awt.Color;

import acm.graphics.*;
import acm.program.*;

public class PickAColor extends GraphicsProgram {
	
	/* width and the height of our moving square */
	private static final int SQUARE_SIZE = 100;
	
	/* instance variables for clickable color rects */
	GRect blueRect;
	GRect redRect;
	GRect yellowRect;
	GRect purpleRect;
	Color currColor;
	
	public void run() {	
		// Add colorful squares
		blueRect = createSquare(0, 0);
		addColorToRect(blueRect, Color.BLUE);
		
		redRect = createSquare(100, 0);
		addColorToRect(redRect, Color.RED);
		
		yellowRect = createSquare(200, 0);
		addColorToRect(yellowRect, Color.YELLOW);
		
		purpleRect = createSquare(300, 0);
		addColorToRect(purpleRect, Color.MAGENTA);
		
		// Add blank squares
		int x = 0;
		while(x < getWidth() - SQUARE_SIZE) {
			createSquare(x, getHeight() - SQUARE_SIZE);
			x += SQUARE_SIZE;
		}
	}
	
	/**
	 * Adds a given color to a given GRect.
	 * 
	 * @param rect
	 * @param color
	 */
	private void addColorToRect(GRect rect, Color color) {
		rect.setFilled(true);
		rect.setColor(color);
	}
	
	/**
	 * Creates a blank, white square at the given x and y.
	 * 
	 * @param x
	 * @param y
	 * @return blank GRect
	 */
	private GRect createSquare(double x, double y) {
		GRect rect = new GRect(x, y, SQUARE_SIZE, SQUARE_SIZE);
		rect.setFilled(false);
		add(rect);
		return rect;
	}
	
	private void mouseClicked(MouseEvent event) {
		double mouseX = event.getX();
		double mouseY = event.getY();
		GObject clickedSquare = getElementAt(mouseX, mouseY);
		
		// If we click on a colored square, choose that color
		// If we click on a blank square, color it in!
		if(clickedSquare == blueRect) {
			currColor = Color.BLUE;
		} else if(clickedSquare == redRect) {
			currColor = Color.RED;
		} else if(clickedSquare == redRect) {
			currColor = Color.YELLOW;
		} else if(clickedSquare == purpleRect) {
			currColor = Color.MAGENTA;
		} else {
			addColorToRect(clickedSquare, currColor);
		}
		
	}
}
