package net.woodyfolsom.msproj;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class GameBoard {
	public static final char BLACK_STONE = 'X';
	public static final char BLACK_TERRITORY = 'x';
	public static final char EMPTY_INTERSECTION = '.';
	public static final char MARKED_GROUP = 'g';
	public static final char MARKED_TERRITORY = '?';
	public static final char UNOWNED_TERRITORY = '-';
	public static final char WHITE_STONE = 'O';
	public static final char WHITE_TERRITORY = 'o';

	private boolean territoryMarked = false;
	private int size;
	private char[] board;
	private List<Integer> captureList;
	private List<Long> boardHashHistory = new ArrayList<Long>();

	private ZobristHashGenerator zobristHashGenerator;

	public GameBoard(int size) {
		this.size = size;
		board = new char[size * size];
		Arrays.fill(board, '.');

		zobristHashGenerator = ZobristHashGenerator.getInstance(size);
		boardHashHistory.add(zobristHashGenerator.getEmptyBoardHash());
		captureList = new ArrayList<Integer>();
	}

	public GameBoard(GameBoard that) {
		this.size = that.size;
		this.board = Arrays.copyOf(that.board, that.board.length);
		zobristHashGenerator = ZobristHashGenerator.getInstance(size);
		boardHashHistory = new ArrayList<Long>(that.boardHashHistory);
		captureList = new ArrayList<Integer>(that.captureList);
	}

	public long getZobristHash() {
		return boardHashHistory.get(boardHashHistory.size() - 1);
	}

	public void clear() {
		territoryMarked = false;
		captureList.clear();
		Arrays.fill(board, EMPTY_INTERSECTION);
	}

	public int countSymbols(char... symbols) {
		int stoneCount = 0;
		for (int i = 0; i < board.length; i++) {
			for (int j = 0; j < symbols.length; j++) {
				if (board[i] == symbols[j]) {
					stoneCount++;
				}
			}
		}
		return stoneCount;
	}

	public List<Integer> getCaptureList() {
		return captureList;
	}

	@Override
	// TODO: implement as Zobrist hash.
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + Arrays.hashCode(board);
		result = prime * result + size;
		result = prime * result + (territoryMarked ? 1231 : 1237);
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		GameBoard other = (GameBoard) obj;
		if (!Arrays.equals(board, other.board))
			return false;
		if (size != other.size)
			return false;
		if (territoryMarked != other.territoryMarked)
			return false;
		return true;
	}

	public static int getColumnIndex(char columnLabel) {
		if (columnLabel < 'I') {
			return columnLabel - 'A';
		} else if (columnLabel > 'I') {
			return columnLabel - 'A' - 1;
		} else {
			throw new IllegalArgumentException("Invalid column label: "
					+ columnLabel);
		}
	}

	public static char getColumnLabel(int columnIndex) {
		if (columnIndex > 7) {
			return (char) ('A' + columnIndex + 1);
		} else {
			return (char) ('A' + columnIndex);
		}
	}

	public static String getCoordinate(int colIndex, int rowIndex) {
		return String.valueOf(getColumnLabel(colIndex)) + (rowIndex + 1);
	}

	public static char getOpponentSymbol(char stoneSymbol) {
		if (stoneSymbol == GameBoard.BLACK_STONE) {
			return GameBoard.WHITE_STONE;
		} else if (stoneSymbol == GameBoard.WHITE_STONE) {
			return GameBoard.BLACK_STONE;
		} else {
			throw new IllegalArgumentException(
					"StoneSymbol must be BLACK_STONE or WHITE_STONE");
		}
	}

	public int getSize() {
		return size;
	}

	/**
	 * @param colLabel
	 *            [A..T] (skipping I
	 * @param rowNumber
	 *            1-based
	 * @return
	 */
	public char getSymbolAt(char colLabel, int rowNumber) {
		return getSymbolAt(getColumnIndex(colLabel), rowNumber - 1);
	}

	public char getSymbolAt(int index) {
		return board[index];
	}

	/**
	 * 0-based.
	 * 
	 * @param col
	 * @param row
	 * @return
	 */
	public char getSymbolAt(int col, int row) {
		try {
			return board[(size - row - 1) * size + col];
		} catch (ArrayIndexOutOfBoundsException ae) {
			ae.printStackTrace();
			throw ae;
		}
	}

	public boolean isEmpty(char col, int row) {
		return getSymbolAt(col, row) == EMPTY_INTERSECTION;
	}

	public boolean isKoViolation() {
		long lastHash = boardHashHistory.get(boardHashHistory.size() - 1);
		for (int i = 0; i < boardHashHistory.size() - 1; i++) {
			if (boardHashHistory.get(i) == lastHash) {
				return true;
			}
		}
		return false;
	}

	public boolean isTerritoryMarked() {
		return territoryMarked;
	}

	public boolean isStarPoint(char col, int row) {
		switch (size) {
		case 3:
			if (col == 'B' && row == 2) {
				return true;
			} else {
				return false;
			}
		case 4:
			return false;
		default:
			return false;
		}
	}

	public boolean markTerritory(int col, int row, char mark) {
		char symbol = getSymbolAt(col, row);
		if (symbol != '.') {
			return false;
		}
		setSymbolAt(col, row, mark);
		return true;
	}

	public boolean removeStone(char colLabel, int rowNum) {
		if (getSymbolAt(colLabel, rowNum) == EMPTY_INTERSECTION) {
			return false;
		}

		setSymbolAt(colLabel, rowNum, EMPTY_INTERSECTION);

		return true;
	}

	public int captureMarkedGroup(char opponentSymbol) {
		int numReplaced = 0;

		for (int i = 0; i < board.length; i++) {
			if (board[i] == MARKED_GROUP) {
				board[i] = opponentSymbol;
				setSymbolAt(i, EMPTY_INTERSECTION);
				captureList.add(i);
				numReplaced++;
			}
		}

		return numReplaced;
	}

	public void clearCaptureList() {
		captureList.clear();
	}

	public void markTerritory(char ownerSymbol) {
		for (int i = 0; i < board.length; i++) {
			if (board[i] == MARKED_TERRITORY) {
				board[i] = ownerSymbol;
			}
		}
	}

	public void unmarkGroup(char opponentSymbol) {
		for (int i = 0; i < board.length; i++) {
			if (board[i] == MARKED_GROUP) {
				board[i] = opponentSymbol;
			}
		}
	}

	// TODO change boardHashHistory to stack
	public void popHashHistory() {
		boardHashHistory
				.remove(boardHashHistory.get(boardHashHistory.size() - 1));
	}

	public void pushHashHistory() {
		boardHashHistory.add(boardHashHistory.get(boardHashHistory.size() - 1));
	}

	public void setSymbolAt(char colLabel, int rowNumber, char symbol) {
		setSymbolAt(getColumnIndex(colLabel), rowNumber - 1, symbol);
	}

	public void setSymbolAt(int index, char newSymbol) {
		char oldSymbol = board[index];

		// TODO marked intersections should really be stored in
		// a separate array to ensure that the hash code is always in sync with
		// an actual or transitional board position
		if (oldSymbol == MARKED_GROUP || newSymbol == MARKED_GROUP
				|| oldSymbol == MARKED_TERRITORY
				|| newSymbol == MARKED_TERRITORY) {
			board[index] = newSymbol;
		} else {
			int hashIndex = boardHashHistory.size() - 1;
			long currentHashCode = boardHashHistory.get(hashIndex);

			board[index] = newSymbol;

			currentHashCode ^= zobristHashGenerator.getHashCode(index,
					oldSymbol);
			currentHashCode ^= zobristHashGenerator.getHashCode(index,
					newSymbol);

			boardHashHistory.set(hashIndex, currentHashCode);
		}
	}

	public void setSymbolAt(int col, int row, char newSymbol) {
		setSymbolAt((size - row - 1) * size + col, newSymbol);
	}

	public void setTerritoryMarked(boolean territoryMarked) {
		this.territoryMarked = territoryMarked;
	}

	public void unmarkTerritory() {
		if (territoryMarked == false) {
			return;
		}

		for (int i = 0; i < board.length; i++) {
			char currentSymbol = board[i];
			if (currentSymbol == BLACK_TERRITORY
					|| currentSymbol == WHITE_TERRITORY
					|| currentSymbol == UNOWNED_TERRITORY) {
				board[i] = EMPTY_INTERSECTION;
			}
		}
		territoryMarked = false;
	}
}