import java.io.*;
import java.util.*;
import javax.swing.*;

/**
 * Class implementing a HiQ, or "Peg" game with a graphical user interface using
 * a grid of clickable buttons to represent a board.
 */
public class HiQ {
  /**
   * Main method. Opens a FileChooser so player can chose a file containing a
   * board representation and then starts the game with that board. 
   * @param args If present, args[0] contains the directory to open
   * in FileChooser.
   */
   public static void main(String[] args) throws IOException {
     JFileChooser chooser;
     // Prompt for a map and read the file.
     if (args.length > 0) {
       chooser = new JFileChooser(args[0]);
     } else {
       chooser = new JFileChooser();
     }
     
     int returnVal = chooser.showOpenDialog(null);
     
     // read the board map from the file into a char[][] array;
     // create a new HiQBoard and pass it the array; create a new 
     // HiQWindow and pass it the board; let window initialize itself
     // All further action takes place in the HiQWindow object.
     if (returnVal == JFileChooser.APPROVE_OPTION) {
       char[][] map = readMap(chooser.getSelectedFile());
       HiQBoard game = new HiQBoard(map);
       HiQWindow window = new HiQWindow(game);
       window.initWindow();
     } 
     // if user does not select a file, exit.
     else {
       System.exit(0);
     }
   }
   
   /**
   * Read a game board from a file, returning the contents in a
   * two-dimensional character array in row-major order.
   * @param f the file to read the board from
   * @return the two-dimensional array contaiing the board
   */
  private static char[][] readMap(File f) throws IOException {
    
    /*
     * Read the file, saving the contents in a big String. We need to do
     * this to count the lines in the file so we know how big to make the
     * char[][].
     */
    BufferedReader br = new BufferedReader(new FileReader(f));
    String textBoard = "";

    String nextLine = br.readLine();
    while (nextLine != null) {
      textBoard = textBoard + nextLine + "\n";
      nextLine = br.readLine();
    }
    
    // Go through the Strings from the file changing them into char[]'s.
    StringTokenizer st = new StringTokenizer(textBoard, "\n");
    char[][] result = new char[st.countTokens()][];
    int nextRow = 0;
    while (st.hasMoreTokens()) {
      result[nextRow] = st.nextToken().toCharArray();
      nextRow++;
    }
    
    br.close();
    return result;
  }
  
}

