package swt.tdd.tictactoe;

public class TicTacToeImpl implements TicTacToe {

	@Override
	public Tile isWinner(Tile[][] board) throws IllegalArgumentException {

		// Check invalid board
		if (board == null || board.length != 3)
			throw new IllegalArgumentException("Invalid board");
		for (Tile[] row : board) {
			if (row.length != 3)
				throw new IllegalArgumentException("Invalid board");
		}		
		
		Tile winner = Tile.NONE;

		// Check rows
		for (Tile[] row : board) {
			if (row[0] == row[1] && row[0] == row[2] && row[0] != Tile.NONE) {
				if (winner != Tile.NONE) {
					throw new IllegalArgumentException("Invalid board");
				}
				winner = (row[0] == Tile.CIRCLE ? Tile.CIRCLE : Tile.CROSS);
			}
		}
		
		// Check columns
		for (int column = 0; column < 3; column++) {
			if (board[0][column] == board[1][column] && board[0][column] == board[2][column] && board[0][column] != Tile.NONE) {
				if (winner != Tile.NONE) {
					throw new IllegalArgumentException("Invalid board");
				}
				winner = (board[0][column] == Tile.CIRCLE ? Tile.CIRCLE : Tile.CROSS);
			}
		}	
		
		// Check diagonals
		if (board[0][0] == board[1][1] && board[0][0] == board[2][2] && board[0][0] != Tile.NONE) {
			winner = (board[0][0] == Tile.CIRCLE ? Tile.CIRCLE : Tile.CROSS);
		}
		if (board[0][2] == board[1][1] && board[0][2] == board[2][0] && board[0][2] != Tile.NONE) {
			winner = (board[0][2] == Tile.CIRCLE ? Tile.CIRCLE : Tile.CROSS);
		}		
		
		return winner;
	}

}
