package net.woodyfolsom.msproj;

public class TerritoryMarker {
	public static final char BLACK_TERRITORY = 'x';
	public static final char WHITE_TERRITORY = 'o';
	public static final char UNOWNED_TERRITORY = '-';
	public static final char TERRITORY_MARKER = '?';

	public static final int EMPTY = 0;
	public static final int BLACK = 1;
	public static final int WHITE = 2;

	public static GameBoard markTerritory(GameBoard gameBoard) {
		for (int row = 0; row < gameBoard.getSize(); row++) {
			for (int col = 0; col < gameBoard.getSize(); col++) {
				char symbol = gameBoard.getSymbolAt(col, row);
				if (symbol != '.') {
					continue;
				}
				int ownedBy = findTerritory(gameBoard, col, row);
				if (ownedBy == BLACK) {
					gameBoard.markTerritory(BLACK_TERRITORY);
				} else if (ownedBy == WHITE) {
					gameBoard.markTerritory(WHITE_TERRITORY);
				} else {
					gameBoard.markTerritory(UNOWNED_TERRITORY);
				}
			}
		}
		gameBoard.setTerritoryMarked(true);
		return gameBoard;
	}

	public static int getStoneColor(GameBoard gameBoard, int col, int row) {
		char symbol = gameBoard.getSymbolAt(col, row);
		if (symbol == GameBoard.BLACK_STONE) {
			return BLACK;
		} else if (symbol == GameBoard.WHITE_STONE) {
			return WHITE;
		} else {
			return EMPTY;
		}
	}

	public static int findTerritory(GameBoard gameBoard, int col, int row) {
		char symbol = gameBoard.getSymbolAt(col, row);

		if (symbol == GameBoard.BLACK_STONE) {
			return BLACK;
		} else if (symbol == GameBoard.WHITE_STONE) {
			return WHITE;
		} else if (symbol == TERRITORY_MARKER) {
			return EMPTY;
		}

		gameBoard.markTerritory(col, row, TERRITORY_MARKER);
		int borderBits = EMPTY;

		if (col > 0) {
			borderBits |= findTerritory(gameBoard, col - 1, row);
		}
		if (col < gameBoard.getSize() - 1) {
			borderBits |= findTerritory(gameBoard, col + 1, row);
		}
		if (row > 0) {
			borderBits |= findTerritory(gameBoard, col, row - 1);
		}
		if (row < gameBoard.getSize() - 1) {
			borderBits |= findTerritory(gameBoard, col, row + 1);
		}

		return borderBits;
	}
}