package ola.jsame;

import javax.swing.*;
import java.awt.event.*;
import java.awt.GridLayout;

public class ButtonPanel extends JPanel
{
    private OOGAButton myButtons[][];
    private SameGameModel myModel;
    private ActionListener myMoveMaker;    
    /**
     * Create a button panel consisting of rows x cols buttons
     */
	
    ButtonPanel(int rows, int cols, SameGameModel model)
    {
	// construct superclass and make button array
	super(new GridLayout(rows,cols));
	myButtons = new OOGAButton[rows][cols];

	// make listener to do the move chosen by user
	myMoveMaker = new ActionListener(){
		public void actionPerformed(ActionEvent e)
		{
		    myModel.makeMove(new SameMove(e.getActionCommand()));
		}
	    };

	myModel = model;
	makeButtons(myMoveMaker);
    }

    /**
     * Makes the buttons for this GUI/view. The number
     * of buttons is determined my the size of the array
     * myButtons. This helper function takes some of
     * the busy work out of the ButtonPanel constructor.
     */
    private void makeButtons(ActionListener moveMaker)
    {
	int count = 0;

	for(int rows = 0; rows < myButtons.length; rows++){
	    for(int cols = 0; cols < myButtons[0].length; cols++) {
		String label = ""+count;
		count++;
		// create button with label reflecting count
		OOGAIcon icon = new OOGAIcon();		    
		myButtons[rows][cols] = new OOGAButton(icon);
		myButtons[rows][cols].setActionCommand(label);
		myButtons[rows][cols].addActionListener(moveMaker);
		add(myButtons[rows][cols]);
	    }
	}
    }

    public void highlight(GridPoint[] list)
    {
	for(int j=0; j < list.length; j++){
	    GridPoint p = list[j];
	    myButtons[p.row][p.col].toggleColor();
	}
	repaint();
    }
        
    /**
     * Set all the buttons by re-displaying them all
     * in the right order. First we remove all the components
     * in this panel (that's the buttons). Then we add the
     * buttons to this panel in the right order based on what
     * the ordering of the buttons in the model is.
     * Finally, we revalidate so the buttons are shown (GUI
     * will redraw as a result of the revalidate).
     */
    public void setGrid(int[][] list)
    {
	for(int j=0; j < list.length; j++){
	    for(int k=0; k < list[0].length; k++) {
		if (list[j][k] != SameGameModel.INVALID){
		    myButtons[j][k].setColor(list[j][k]);
		    myButtons[j][k].setEnabled(true);
		}
		else {
		    myButtons[j][k].setColor(-1);
		    myButtons[j][k].setEnabled(false);
		}
	    }
	}
	revalidate();
    }
}
