/*
 * File: MatchingGame.java
 * -----------------------
 * Implements the matching game.
 */

import java.awt.Color;
import java.awt.event.MouseEvent;

import acm.graphics.*;
import acm.program.*;
import acm.util.RandomGenerator;

public class MatchingGame extends GraphicsProgram {
		
	private static final double NUM_ROWS = 5;
	private static final double NUM_COLS = 5;
		
	// tracks the first of two cards that a user clicks
	private GRect card1;
	
	public void run() {
		// draw board
		double cardWidth = getWidth() / NUM_COLS;
		double cardHeight = getHeight() / NUM_ROWS;
		
		for (int r = 0; r < NUM_ROWS; r++) {
			for (int c = 0; c < NUM_COLS; c++) {
				GRect square = new GRect(c * cardWidth, r * cardHeight, cardWidth, cardHeight);
				
				
				Color fillColor = getRandomColor();
				Color borderColor = getRandomColor();
				square.setFilled(true);
				square.setFillColor(fillColor);
				square.setColor(borderColor);
				
				add(square);
			}
		}
	}
	
	public void mouseClicked(MouseEvent e) {
		double x = e.getX();
		double y = e.getY();
		
		GRect elem = getElementAt(x, y);
		if (elem != null) {
			if (card1 == null) {
				// if card1 is null, this is the first of two cards the user  
                // has clicked: store that card in our instance variable
				card1 = elem;
			} else if (elem != card1) {
				// if we get here, the user has clicked a second card
				
				// remove them if they have the same color and fill color
				if (elem.getColor() == card1.getColor() && elem.getFillColor() == card1.getFillColor()) {
					remove(card1);
					remove(elem);
				}
				
				// clear user selection: reset card1 to null
				card1 = null;
			}
		}
	}
	
	/*
	 * getRandomColor
	 * --------------
	 * Gets a random color. You can assume this method was already
	 * provided for you on the midterm.
	 */
	private Color getRandomColor() {
		int n = RandomGenerator.getInstance().nextInt(3);
		if (n == 0) return Color.BLUE;
		if (n == 1) return Color.YELLOW;
		return Color.GREEN;
	}
}
