import javax.swing.*;

public class TTTDriver {
  
  private static final char PLAYER_ONE = 'X';
  private static final char PLAYER_TWO = 'O';
  
  /**
   * A java application is a set of one or more classes
   * with (at least) one main method.
   * 
   * To start executing the program, the system 
   * executes the main method.
   */ 
  public static void main(String[] args) {
    
    // check for an incorrect number of arguments
    if (args.length > 1) {
      System.exit(0); // exit the program
    }
    
    TicTacToe t = new TicTacToe();
    TTTWindow w = new TTTWindow(t);
    
    char currPlayer;
    
    // if there is an args[0], it indicates who plays first.
    if (args.length == 1) {
      currPlayer = args[0].charAt(0);
    } else { // initialize to default
      currPlayer = PLAYER_ONE;
    }
    
    // while it's not a draw and no one has won yet
    while (!t.isDraw() && t.getWinner() == TicTacToe.BLANK_SQUARE) {
      
      // the player makes a move
      int r = Integer.parseInt(JOptionPane.showInputDialog(null,
                                                           "Player " + currPlayer + " enter a row:"));
      
      int c = Integer.parseInt(JOptionPane.showInputDialog(null,
                                                           "Player " + currPlayer + " enter a column:"));
      
      // use a try-catch block to "catch" a TTTException.
      // this happens when the user enters a row and/or column
      // that is greater than 2.
      try {
        //put the mark on the board
          t.setMark(currPlayer, r, c);
      } catch (TTTException e) {
        JOptionPane.showMessageDialog(null, e.getMessage());
        System.exit(0);
      }
      
      // update the window
      w.update(r, c);
      
      // switch players
      if (currPlayer == PLAYER_ONE) {
        currPlayer = PLAYER_TWO;
      } else if (currPlayer == PLAYER_TWO) {
        currPlayer = PLAYER_ONE;
      } else {
        System.exit(0);
      }
    }
    
    if (t.getWinner() != TicTacToe.BLANK_SQUARE) { // someone wins
      JOptionPane.showMessageDialog(null, "Player " + t.getWinner() + " won!");
    } else { // it's a draw
      JOptionPane.showMessageDialog(null, "It's a draw!");
    }
    
  }
  
}
