import javax.swing.JButton;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

import javax.swing.JFrame;


/**
 * In this game, the user is presented with an array of buttons that are 
 * initialized randomly to either black or white. Clicking on a button 
 * changes the color of the button and its two neighbors, if they exist. 
 * The object of the game is to reach a state when the buttons are all 
 * the same color. If this happens, something signals the win (how is 
 * up to you). Finish the code!
 *
 * @author Matt Boutell.
 */
public class TogglerFrame extends JFrame {
	private ArrayList<ColorToggleButton> buttonList;

	/**
	 * Starts here.
	 *
	 * @param args
	 */
	public static void main(String[] args) {
		int nButtons = 7; // could vary, of course!
		TogglerFrame frame = new TogglerFrame(nButtons);
		frame.setVisible(true);
		while(true)
		{
			if (frame.won())
			{
				frame.setTitle("You win!");
				//frame.dispose();
			}
		}
	}
	
	/**
	 * Tests to see if the game is won.
	 *
	 * @return boolean, won or no.
	 */
	public boolean won()
	{
		boolean win=true;
		for (int i = 0; i<this.buttonList.size()-1;i++)
		{
			if (!(this.buttonList.get(i).getBackground() == this.buttonList.get(i+1).getBackground()))
			{
				win=false;
			}
		}
		return win;
	}

	/**
	 * Create a frame with the given number of buttons in it. 
	 * You are given the typical frame code to start.
	 * 
	 * @param nButtons The number of buttons to draw.
	 */
	public TogglerFrame(int nButtons) {
		this.setTitle("Toggler, by Matt Boutell");
		this.setSize(new Dimension(800, 100));
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setLayout(new FlowLayout());
		this.buttonList = new ArrayList<ColorToggleButton>(nButtons);
		for (int i=0; i<=nButtons;i++)
		{
			ColorToggleButton b = new ColorToggleButton("", Color.black, Color.white);
			if (Math.random() <= 0.5)
			{
				b.setBackground(Color.black);
			}
			else
				b.setBackground(Color.white);
			this.buttonList.add(b);
			this.add(b);
		}
		
		for (int i = 0; i<this.buttonList.size();i++)
		{
			ColorToggleButton b = this.buttonList.get(i);
			b.addActionListener(b);
			if (i ==0)
			{
				b.addActionListener(this.buttonList.get(i+1));
				continue;
			}
			if (i==this.buttonList.size()-1)
			{
				b.addActionListener(this.buttonList.get(i-1));
				continue;
			}
			b.addActionListener(this.buttonList.get(i+1));
			b.addActionListener(this.buttonList.get(i-1));
		}
	}

}
