package net.woodyfolsom.msproj;

public class LibertyCounter {
	public static int countLiberties(GameBoard gameBoard, char colLabel,
			int rowNum, char groupColor) {
		return countLiberties(gameBoard, GameBoard.getColumnIndex(colLabel),
				rowNum - 1, groupColor, false);
	}

	public static int countLiberties(GameBoard gameBoard, int col, int row,
			char groupColor, boolean markGroup) {
		int liberties = markGroup(gameBoard, col, row, groupColor);

		if (!markGroup) {
			gameBoard.unmarkGroup(groupColor);
		}

		return liberties;
	}

	public static int markGroup(GameBoard gameBoard, int col, int row,
			char groupColor) {
		char stoneSymbol = gameBoard.getSymbolAt(col, row);
		if (stoneSymbol == GameBoard.EMPTY_INTERSECTION) {
			return 1; // one liberty
		}
		if (stoneSymbol == GameBoard.MARKED_GROUP) {
			return 0; // intersection already counted
		}
		if (stoneSymbol == groupColor) {
			int liberties = 0;
			gameBoard.setSymbolAt(col, row, GameBoard.MARKED_GROUP);
			if (col > 0) {
				liberties += markGroup(gameBoard, col - 1, row, groupColor);
			}
			if (col < gameBoard.getSize() - 1) {
				liberties += markGroup(gameBoard, col + 1, row, groupColor);
			}
			if (row > 0) {
				liberties += markGroup(gameBoard, col, row - 1, groupColor);
			}
			if (row < gameBoard.getSize() - 1) {
				liberties += markGroup(gameBoard, col, row + 1, groupColor);
			}
			return liberties;
		}

		if (groupColor == GameBoard.WHITE_STONE
				&& stoneSymbol == GameBoard.BLACK_STONE) {
			return 0; // opposing stone - not a liberty
		}
		if (groupColor == GameBoard.BLACK_STONE
				&& stoneSymbol == GameBoard.WHITE_STONE) {
			return 0; // opposing stone - not a liberty
		}

		throw new IllegalStateException(
				"Cannot continue marking group - symbol at current location is not empty intersection, white stone, black stone or group marker");
	}
}
