package tictactoe.app;
import tictactoe.trans.TTTHandler;
import java.io.Serializable;
import util.*;

/**
 * The "application" component of a Tic-Tac-Toe program.  Should be
 * instantiated and managed by an instance of {@link pres.TTTHandler}.
 *
 * @author Thomas P. Hayes
 * @version 1.0
 */
public class TTTApplication implements Serializable {
    
    public static final int EMPTY = TTTHandler.EMPTY;
    public static final int EX = TTTHandler.EX;
    public static final int OH = TTTHandler.OH;
    /** An 3x3 array of ints representing the contents of the board. */
    protected int[][] board;
    protected int whoseMove;
    protected TTTHandler handler = null;
    
    public TTTApplication() {
	board = new int[3][];
	for (int i=0; i<3; i++) {
	    board[i] = new int[3];
	    for (int j=0; j<3; j++)
		board[i][j] = EMPTY;
	}
	whoseMove = EX;	    
    }
    
    public void setHandler (TTTHandler h) {
	handler = h;
	handler.setMover(whoseMove);
    }

    /** 
     * Moves to the given square, if legal.
     *
     * @param where The square to move to.  
     * @return <code>true</code> if the move succeeded, 
     * <code>false</code> if not.
     */
    public boolean makeMove(int where) {
	Debug.print("makeMove("+where+")");
	if ((where < 0) || (where >= 9)) {
	    Debug.print("TTTApplication.makeMove: square out of range.");
	    return false;
	}
	if (board[where/3][where%3] == EMPTY) {
	    board[where/3][where%3] = whoseMove;
	    handler.displayMove(where,whoseMove);
	    // Check for win.
	    boolean wonGame = true;
	    for (int i=0; i<3; i++)
		if (board[i][where%3] != whoseMove)
		    wonGame = false;
	    if (!wonGame) {
		wonGame = true;
		for (int i=0; i<3; i++)
		    if (board[where/3][i] != whoseMove)
			wonGame = false;
	    }
	    if (!wonGame) {
		wonGame = true;
		for (int i=0; i<3; i++)
		    if (board[i][i] != whoseMove)
			wonGame = false;
	    }
	    if (!wonGame) {
		wonGame = true;
		for (int i=0; i<3; i++)
		    if (board[i][2-i] != whoseMove)
			wonGame = false;
	    }
	    if (wonGame) { 
		handler.wonGame(whoseMove);
		return true;
	    } else {
		if (whoseMove == EX)
		    whoseMove = OH;
		else whoseMove = EX; 
		handler.setMover(whoseMove);
		return true;
	    } 
	}
	return false;
    }
    
    public void resetBoard() {
	for (int i=0; i<3; i++)
	    for (int j=0; j<3; j++) {
		board[i][j] = EMPTY;
		handler.displayMove(3*i+j,EMPTY);
	    }
	whoseMove = EX;
	handler.setMover(whoseMove);
    }
}
