package tictactoe.pres;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import util.*;

public class TTTGamePanel extends ActionPanel {

    protected JPanel[] rowPanel;
    protected JPanel[][] spotPanel;
    protected JButton[][] spotButton;

    /**
     * Construct a new Panel containing the TicTacToe game presentation
     * elements.
     */
    public TTTGamePanel () {
	this.setLayout(new GridLayout(3,0));
	rowPanel = new JPanel[3];
	spotPanel = new JPanel[3][];
	spotButton = new JButton[3][];
	for (int i=0; i<3; i++) {
	    rowPanel[i] = new JPanel();
	    rowPanel[i].setLayout(new GridLayout(0,3));
	    spotPanel[i] = new JPanel[3];
	    spotButton[i] = new JButton[3];
	    for (int j=0; j<3; j++) {
		spotPanel[i][j] = new JPanel();
		spotButton[i][j] = new JButton();
		spotButton[i][j].setBackground(Color.white);
		spotButton[i][j].setActionCommand("TTT" + (3*i+j));
		spotPanel[i][j].add(spotButton[i][j]);
		rowPanel[i].add(spotPanel[i][j]);
	    }
	    this.add(rowPanel[i]);
	}
    }
    
    /**
     * Registers <code>listener</code> to receive ActionEvents
     * from the reactive subcomponents of the TTTFrame.  This
     * wrapper function invokes the addActionListener method of each
     * subcomponent.
     *
     * @param listener Event handler to register with the 
     * TTTGamePanel components.
     */
    public void addActionListener(ActionListener listener) {
	for (int i=0; i<3; i++)
	    for (int j=0; j<3; j++)
		spotButton[i][j].addActionListener(listener);
    }
    
    public void enableMove (int where, boolean moveAllowed) {
	if ((where < 0) || (where >= 9))
	    Debug.print("TTTGamePanel.enableMove: Invalid location.");
	else
	    spotButton[where/3][where%3].setEnabled(moveAllowed);
    }

    public void setEnabledButtons(JButton styleButton) {
	for (int i=0; i<3; i++)
	    for (int j=0; j<3; j++)
		if (spotButton[i][j].isEnabled()) {
		    Copy.aBtoAB(spotButton[i][j], styleButton);
		}   
    }

    /**
     * Runs a quick test of the class code.
     *
     * @param args Command-line arguments (ignored).
     */
    public static void main (String[] args) {
	JFrame f = new JFrame();
	TTTGamePanel gamePanel = new TTTGamePanel();
	gamePanel.addActionListener(new ActionListener() {
		public void actionPerformed(ActionEvent e) {
		    System.out.println("ActionCommand: "+e.getActionCommand());
		    System.out.println("Action source: "+e.getSource());
		}});
	f.getContentPane().add(gamePanel);
	f.pack();
	f.setVisible(true);
	f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    
}

