/*
 *   Author: Florian Fink, 2014
 *   Based on Code by: veqryn
 *   
 *   This project is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version.
 *
 *   This project is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License along with this project. If not, see http://www.gnu.org/licenses/.
 */
package usergames.othello;

import games.strategy.common.player.AbstractBaseAI;
import games.strategy.engine.data.GameData;
import games.strategy.engine.data.PlayerID;
import games.strategy.engine.data.Territory;
import games.strategy.engine.data.Unit;
import games.strategy.engine.data.UnitType;
import games.strategy.grid.delegate.remote.IGridPlayDelegate;
import games.strategy.grid.player.IGridGamePlayer;
import games.strategy.grid.ui.GridPlayData;
import games.strategy.grid.ui.IGridPlayData;

import java.util.Collection;
import java.util.Random;

import usergames.othello.othelloDelegate.PlayDelegate;

/**
 * A completely random AI for the Othello game
 */
public class RandomOthelloAI extends AbstractBaseAI implements IGridGamePlayer {

	public RandomOthelloAI(String name, String type) {
		super(name, type);
	}

	@Override
	public void start(String stepName) {
		super.start(stepName);

		if (stepName.endsWith("Play")) // as defined in xml
			doRandomMove();

		// else do nothing
	}

	protected void doRandomMove() {
		pause();

		IGridPlayDelegate playDel = (IGridPlayDelegate) this.getPlayerBridge()
				.getRemoteDelegate();

		// find a random move
		IGridPlayData move = null;
		Collection<IGridPlayData> allMoves = PlayDelegate.getAllPossibleMoves(
				getPlayerID(), getGameData());
		if (!allMoves.isEmpty()) { // can we make a valid move?
			Random r = new Random();
			int index = r.nextInt(allMoves.size());

			int i = 0;
			for (IGridPlayData m : allMoves) {
				if (index == i) {
					move = m;
					break;
				}
				i++;
			}
		}
		else //no valid move
			move=new GridPlayData(true, getPlayerID()); //skip

		// perform play
		playDel.play(move);

	}

	@Override
	public UnitType selectUnit(Unit startUnit, Collection<UnitType> options,
			Territory territory, PlayerID player, GameData data, String message) {
		return null;
	}

}
