/**
 * class Board
 *
 * Represents a position on the board and also contains methods for making
 * and unmaking a move, as well as generating all possible (legal) moves on
 * the board.
 *
 * @author Jonatan Pettersson (jonatan_pettersson@hotmail.com)
 * Date: 2006-12-14
 * Last update: 2006-12-16
 */

public class Board implements Definitions
{
	// ***
	// Variables used to describe the position
	// ***
	
	private int[] boardArray = new int[128]; 	// Represents the 0x88 board

	private int toMove; 				// Side to move on the board

	private int enPassant;  			// Index on boardArray where en passant is
							// available, -1 if none

	private int white_castle;			// White's ability to castle
	private int black_castle; 			// Black's ability to castle

	private int movesFifty;				// Keeps track of half-moves since last capture
							// or pawn move
	private int movesFull; 				// Keeps track of total full moves in the game

	//END Variables

	/**
	 *  Creates an empty board
	 *
	 *  @return An empty Board
	 */
	public Board()
	{
		this.toMove = 1; // White to move
		this.enPassant = -1; // No en passants available
		this.white_castle = CASTLE_NONE;
		this.black_castle = CASTLE_NONE;
	}
	// END Board()

	/**
	 *  Makes a Move on the board
	 *
	 *  @param Move move
	 */
	public void makeMove(Move move)
	{

	}
	// END makeMove()

	/**
	 *  Returns the current position in FEN-notation
	 *
	 *  @return A string with FEN-notation
	 */
	public String getFEN()
	{
		String fen_string = ""; // This holds the FEN-string

		// ***
		// The following lines adds the pieces and empty squares to the FEN
		// ***

		int index = 112; // Keeps track of the index on the board
		int empties = 0; // Number of empty squares in a row

		while (index >= 0) // Run until end of the real board
		{
			if((index & 0x88) != 0) // Reached the end of a rank
			{
				if(empties != 0)
				{
					fen_string += empties; // Add the empties number if it's not 0
					empties = 0;
				}
				index -= 24; // Jump to the next rank
				if(index >= 0) fen_string += "/"; // Add to mark a new rank, if we're not at the end
			}	      
			else // The index is on the real board
			{
				if(boardArray[index] != EMPTY_SQUARE) // If a piece is on the square
					// i.e. the square it not empty
				{
					if(empties != 0) fen_string += empties; // Add the empty square number
					// if it's not 0
					empties = 0; // Reset empties (since we now have a piece coming)
				}

				switch(boardArray[index])
				{
					// Add the piece on the square
					case W_KING: fen_string += "K";	break;
					case W_QUEEN: fen_string += "Q"; break;
					case W_ROOK: fen_string += "R";	break;
					case W_BISHOP: fen_string += "B"; break;
					case W_KNIGHT: fen_string += "N"; break;
					case W_PAWN: fen_string += "P"; break;
					case B_KING: fen_string += "k";	break;
					case B_QUEEN: fen_string += "q"; break;
					case B_ROOK: fen_string += "r"; break;
					case B_BISHOP: fen_string += "b"; break;
					case B_KNIGHT: fen_string += "n"; break;
					case B_PAWN: fen_string += "p";	break;
					default: empties++; // If no piece, increment the empty square count
				}
				index++; // Go to the next square
			}


		}

		// END Adding pieces
		
		fen_string += " "; // Add space for next part

		// Adds side to move (important space before the letter here)
		if(toMove == WHITE_TO_MOVE) fen_string += "w"; // White's move
		else fen_string += "b"; // Black's move

		fen_string += " "; // Add space for next part

		// Castling rights
		if(white_castle == CASTLE_NONE && black_castle == CASTLE_NONE) fen_string += "-"; // Neither
		else // Atleast one side can castle one way
		{
			switch(white_castle) // Check white's castling rights
			{
				case CASTLE_SHORT: fen_string += "K"; break;
				case CASTLE_LONG: fen_string += "Q"; break;
				case CASTLE_BOTH: fen_string += "KQ"; break;
			}

			switch(black_castle) // Check black's castling rights
			{
				case CASTLE_SHORT: fen_string += "k"; break;
				case CASTLE_LONG: fen_string += "q"; break;
				case CASTLE_BOTH: fen_string += "kq"; break;
			}
		}

		fen_string += " "; // Add space for next part

		// En passant square
		
		if(enPassant == -1) fen_string += "-"; // If no en passant is available
		else // An en passant is available
		{
			switch(enPassant%16) // Find the row
			{
				case 0: fen_string += "a"; break;
				case 1: fen_string += "b"; break;
				case 2: fen_string += "c"; break;
				case 3: fen_string += "d"; break;
				case 4: fen_string += "e"; break;
				case 5: fen_string += "f"; break;
				case 6: fen_string += "g"; break;
				case 7: fen_string += "h"; break;
				default: fen_string += "Error in ep square";
			}
			switch((enPassant-(enPassant%16))/16) // Find the rank
			{
				case 2: fen_string += "3"; break;
				case 5: fen_string += "6"; break;
				default: fen_string += "Error in ep square"; // Since en passants only can occur
					 				     // on 3rd and 6th rank, any other
									     // rank is an error
			}
		}

		fen_string += " "; // Add space for next part
		fen_string += movesFifty; // Add half-moves since last capture/pawn move
		fen_string += " ";
		fen_string += movesFull; // Add number of full moves in the game so far

		return fen_string; // Returns the finished FEN-string
	}
	// END getFEN()

	/**
	 *  Takes a FEN-string and sets the board accordingly
	 *
	 * @param String fen
	 */
	public void inputFEN(String fen)
	{
		String trimmedFen = fen.trim(); // Removes any white spaces in front or behind the string
		boardArray = new int[128]; // Empties the board from any pieces
		
		String currentChar; // Holds the current character in the fen

		int i = 0; // Used to go through the fen-string character by character

		int boardIndex = 112; // Keeps track of current index on the board (while adding pieces)
				      // Starts at "a8" (index 112) since the fen string starts on this square

		int currentStep = 0; // This will be incremented when a space is detected in the string
				     // 0 - Pieces
				     // 1 - Side to move
				     // 2 - Castling rights
				     // 3 - En passant square
				     // 4 - Half-moves (for 50 move rule) and full moves

		white_castle = CASTLE_NONE; // Resetting, will be changed below if castling rights are found
		black_castle = CASTLE_NONE;
		boolean fenFinished = false; // Set to true when we're at the end of the fen-string
		while(!fenFinished && i < trimmedFen.length())
		{
			currentChar = trimmedFen.substring(i,i+1); // Gets the current character from the fen-string

			// If a space is detected, get the next character, and move to next step
			if(currentChar.equals(" ")) 
			{
				i++;
				currentChar = trimmedFen.substring(i,i+1);
				currentStep++;
			}


			switch(currentStep) // Determine what step we're on
			{
				case 0: // Pieces
				{
					switch(currentChar.charAt(0)) // See what piece is on the square
					{
						// If character is a '/' move to first row on next rank
						case '/': boardIndex -= 24; break;

						// If the character is a piece, add it and move to next square
						case 'K': boardArray[boardIndex] = W_KING; boardIndex++; break;
						case 'Q': boardArray[boardIndex] = W_QUEEN; boardIndex++; break;
						case 'R': boardArray[boardIndex] = W_ROOK; boardIndex++; break;
						case 'B': boardArray[boardIndex] = W_BISHOP; boardIndex++; break;
						case 'N': boardArray[boardIndex] = W_KNIGHT; boardIndex++; break;
						case 'P': boardArray[boardIndex] = W_PAWN; boardIndex++; break;
						case 'k': boardArray[boardIndex] = B_KING; boardIndex++; break;
						case 'q': boardArray[boardIndex] = B_QUEEN; boardIndex++; break;
						case 'r': boardArray[boardIndex] = B_ROOK; boardIndex++; break;
						case 'b': boardArray[boardIndex] = B_BISHOP; boardIndex++; break;
						case 'n': boardArray[boardIndex] = B_KNIGHT; boardIndex++; break;
						case 'p': boardArray[boardIndex] = B_PAWN; boardIndex++; break;

						// If no piece was found, it has to be a number of empty squares
						// so move to that board index
						default: boardIndex += Integer.parseInt(currentChar);
					}
				}
				case 1: // Side to move
				{
					if(currentChar.equals("w")) toMove = WHITE_TO_MOVE;
					else toMove = BLACK_TO_MOVE;
					break;
				}
				case 2: // Castling rights
				{
					// '-' states that no castling is available so we simply keep the values
					// we set before the while-loop, and don't need to do anything here.
					switch(currentChar.charAt(0))
					{
						// White can atleast castle short
						case 'K': white_castle = CASTLE_SHORT; break;

						case 'Q': // White can atleast castle long
						{
							// If white already can castle short, do both, else only long
							if(white_castle == CASTLE_SHORT) white_castle = CASTLE_BOTH;
							else white_castle = CASTLE_LONG;
							break;
						}
						// Black can atleast castle short
						case 'k': black_castle = CASTLE_SHORT; break;

						case 'q': // Black can atleast castle long
						{
							// If black already can castle short, do both, else only long
							if(black_castle == CASTLE_SHORT) black_castle = CASTLE_BOTH;
							else black_castle = CASTLE_LONG;
							break;
						}
					}
					break;					
				}
				case 3: // En passant
				{
					if(currentChar.equals("-")) enPassant = -1;
					else
					{
						switch(currentChar.charAt(0)) // Find the row
						{
							case 'a': enPassant = 0; break;
							case 'b': enPassant = 1; break;
							case 'c': enPassant = 2; break;
							case 'd': enPassant = 3; break;
							case 'e': enPassant = 4; break;
							case 'f': enPassant = 5; break;
							case 'g': enPassant = 6; break;
							case 'h': enPassant = 7; break;
						}
						// Get the next character (the rank)
						i++;
						currentChar = trimmedFen.substring(i,i+1);

						// On rank 3 or else rank 6
						if(currentChar.equals("3")) enPassant += 32; // Add 2 rows to index
						else enPassant += 80; // Add 5 rows to index
					}
					break;
				}
				case 4: // Half-moves (50 move rule) and full moves
				{
					// If the next character is a space, we're done with half-moves and
					// can insert them
					if(trimmedFen.substring(i+1,i+2).equals(" "))
					{
						movesFifty = Integer.parseInt(currentChar);
					}
					// If the next character is not a space, we know it's a number
					// and since half-moves can't be higher than 50 (or it can, but the game
					// is drawn so there's not much point to it), we can assume
					// there are two numbers and then we're done with half-moves.
					else
					{
						movesFifty = Integer.parseInt(trimmedFen.substring(i,i+2));
						i++;
					}
					i += 2;
					movesFull = Integer.parseInt(trimmedFen.substring(i));
					fenFinished = true; // We're done with the fen-string and can exit the loop
					break;
				}
			}
			i++; // Move to the next character in the fen-string
		}
		


	}
	// END inputFEN()
	
	

}
