package net.woodyfolsom.msproj.policy;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import net.woodyfolsom.msproj.Action;
import net.woodyfolsom.msproj.GameConfig;
import net.woodyfolsom.msproj.GameState;
import net.woodyfolsom.msproj.Player;

public class RandomMovePolicy implements Policy, ActionGenerator {
	//private final boolean passWhenLosing = false;
	
	/**
	 * Does NOT modify the gameState.
	 */
	public Action getAction(GameConfig gameConfig, GameState gameState,
			Collection<Action> prohibitedMoves, Player player) {
		return getActions(gameConfig, gameState, prohibitedMoves, player, 1).get(0);
	}

	/**
	 * Attempts to generate up to nMoves random moves on behalf of the specified
	 * player. Will return at least one move, which may be 'NONE' if random
	 * search does not succeed in discovering a valid move. Does NOT modify the
	 * gameState.
	 * 
	 * @param gameConfig
	 * @param gameState
	 * @param color
	 * 
	 * @return
	 */
	public List<Action> getActions(GameConfig gameConfig, GameState gameState,
			Collection<Action> prohibitedMoves, Player player, int nMoves) {
		if (player != gameState.getPlayerToMove()) {
			throw new IllegalArgumentException("It is not " + player
					+ "'s turn to move!");
		}

		GameState gameStateCopy = new GameState(gameState);
		ActionGenerator actionGenerator = new ValidMoveGenerator();

		List<Action> possibleActions = actionGenerator.getActions(gameConfig,
				gameStateCopy, prohibitedMoves, player,
				ActionGenerator.ALL_ACTIONS);
		List<Action> randomActions = new ArrayList<Action>();

		while (possibleActions.size() > 0 && randomActions.size() < nMoves) {
			Action randomAction = possibleActions
					.remove((int) (Math.random() * possibleActions.size()));

			randomActions.add(randomAction);
		}

		if (randomActions.size() == 0) {
			randomActions.add(Action.NONE);
		}

		return randomActions;
	}

	/**
	 * RandomMoveGenerator does not evaluate any states, but simply returns
	 * elements of a set of uniformly distributed, distinct valid moves.
	 * 
	 * @return
	 */
	public int getNumStateEvaluations() {
		return 0;
	}

	@Override
	public List<Action> getActions(GameConfig gameConfig, GameState gameState,
			Player color, int numActions) {
		return getActions(gameConfig, gameState, new ArrayList<Action>(),
				color, numActions);
	}

	@Override
	public Action getAction(GameConfig gameConfig, GameState gameState,
			Player player) {
		return getActions(gameConfig, gameState, player, 1).get(0);
	}

	@Override
	public void setState(GameState gameState) {
		// TODO Auto-generated method stub
		
	}
}