//
// LocalTTTTest.java: simple test of TTTBoard.java
//

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

public class LocalTTTTest extends JFrame implements ActionListener
{ 
   protected JButton[][] squares;
   protected JLabel statusLabel = new JLabel();
   protected TTTBoard board = new TTTBoard();

   public LocalTTTTest()
   {
      super("Tic Tac Toe, Distributed");
      setSize(650, 400); // larger than needed; resizing done below

      // a bit of magic to halt the application if the user closes the window
      addWindowListener(
         new WindowAdapter() {
         public void windowClosing(WindowEvent event) { System.exit(0); }
         });

      // main box; everything placed in this
      JPanel box = new JPanel();
      box.setLayout(new BoxLayout(box, BoxLayout.Y_AXIS));
      getContentPane().add(box);

      box.add(statusLabel, BorderLayout.NORTH);

      // set up the x's and o's
      JPanel xs_and_os = new JPanel();
      xs_and_os.setLayout(new GridLayout(3, 3, 5, 5));
      box.add(xs_and_os);

      squares = new JButton[3][3];
      for(int row = 0; row < 3; ++row)
      {
         for(int col = 0; col < 3; ++col)
         {
            squares[row][col] = new JButton();
            xs_and_os.add(squares[row][col]);
            squares[row][col].addActionListener(this);
         }
      }

      resetBoard();
      
      // resize frame
      pack();
      setSize(300, 300);
   }

   protected void resetBoard()
   {
      for(int row = 0; row < 3; ++row)
         for(int col = 0; col < 3; ++col)
            squares[row][col].setText(" ");
      setCommand();
   }

   protected void setCommand()
   {
      char w = board.winner();
      if ( w == ' ' )
         statusLabel.setText("Click on " + board.turn() + " square");
      else
         statusLabel.setText("Winner: " + w);
   }

   public void actionPerformed(ActionEvent event)
   {
      for(int row = 0; row < 3; ++row)
         for(int col = 0; col < 3; ++col)
            if ( event.getSource() == squares[row][col] )
            {
               if ( board.isOpen(col, row) )
               {
                  board.pick(col, row);
                  squares[row][col].setText(board.ownerStr(col, row));
                  setCommand();
               }
               return;
            }
   }

   public static void main(String[] args)
   {
      LocalTTTTest bd = new LocalTTTTest();
      bd.setVisible(true);
   }
}
