package org.amc.game.chess.computer;

import org.amc.game.chess.AbstractChessGame;
import org.amc.game.chess.ChessBoard;
import org.amc.game.chess.ChessBoard.ChessPieceLocation;
import org.amc.game.chess.IllegalMoveException;
import org.amc.game.chess.KingInCheck;
import org.amc.game.chess.Move;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

public class SimplePlayerStrategy implements ComputerPlayerStrategy {
	
	static final String ERROR_NO_MOVE = "There are no moves available";
	
	private static final KingInCheck kingInCheck = KingInCheck.getInstance();

	final static ThreadLocalRandom random = ThreadLocalRandom.current(); 
	@Override
	public void makeMove(AbstractChessGame chessGame) throws IllegalMoveException {
		Move move = getNextMove(chessGame);
		chessGame.move(chessGame.getCurrentPlayer(), move);
	}

	@Override
	public Move getNextMove(AbstractChessGame chessGame) {
		List<Move> possibleMoves = new ArrayList<>();
		List<ChessPieceLocation> pieceLoc = chessGame.getChessBoard().getListOfPieces(chessGame.getCurrentPlayer());
		
		pieceLoc.forEach(piece -> {
			piece.getPiece().getPossibleMoveLocations(chessGame.getChessBoard(), piece.getLocation()).forEach(loc -> {
				possibleMoves.add(new Move(piece.getLocation(), loc));
			});
		});
		
		return getNextMove(chessGame, possibleMoves);
	}
	
	private Move getNextMove(AbstractChessGame chessGame, List<Move> possibleMoves) {
		if(possibleMoves.isEmpty()) {
			throw new AssertionError(ERROR_NO_MOVE);
		}
		
		int index = random.nextInt(0, possibleMoves.size());
		
		Move move = possibleMoves.get(index);
		
		ChessBoard testBoard = new ChessBoard(chessGame.getChessBoard());
		
		testBoard.move(move);
		
		if(kingInCheck.isPlayersKingInCheck(chessGame.getCurrentPlayer(), chessGame.getOpposingPlayer(chessGame.getCurrentPlayer()), testBoard)) {
			possibleMoves.remove(index);
			return getNextMove(chessGame, possibleMoves);
		}
		return move;
	};

}

@@ -167,24 +167,113 @@
 ceLocation;%0A
+import org.amc.game.chessserver.ComputerServerChessGame;%0Aimport org.apache.log4j.Logger;%0A
 import org.a
@@ -696,16 +696,103 @@
 tance();
+%0A%09%0A%09private static final Logger LOGGER = Logger.getLogger(SimplePlayerStrategy.class); 
 %0A%0A%09final
@@ -1488,16 +1488,85 @@
 %09%7D);%0A%09%09%0A
+%09%09LOGGER.info(%22No of possible moves is %22 + possibleMoves.size());%0A%09%09%0A
 %09%09return

add logger to SimplePlayerStrategy