package game.goals;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.Random;

import game.Game;
import game.Goal;
import game.Player;
import game.map.Castle;

/**
 * Be the first to capture all flag goals
 * @author joachim
 *
 */
public class CaptureTheFlagGoal extends Goal {

	final static boolean DEBUG = false;
	
	final static int MIN_ROUND_FOR_WIN = 2;
	final static int NUM_FLAG_CASTLES_MULTIPLIER = 2;
	
	List<Castle> flagCastles;
	int numFlagCastles;
	
	private static Random random = new Random();
	
	/**
	 * Generates a random integer in this interval
	 * @param min The minimum number
	 * @param max The maximum number
	 * @return The random number
	 */
	private static int newRandomInt(int min, int max) {
		return min + random.nextInt(max - min + 1);
	}
	
	/**
	 * Creates a new capture the flag goal
	 */
	public CaptureTheFlagGoal() {
		super("Capture the flag", "Derjenige Spieler gewinnt, der zuerst"
				+ " alle weiß umrandeten Flaggen-Schlösser erobert.");
		
		flagCastles = new ArrayList<Castle>();
		
		if (DEBUG)
			System.out.println("Creating capture the flag goal instance");
	}
	
	@Override
	public void setGame(Game game) {
		
		super.setGame(game);
		
		flagCastles = new ArrayList<Castle>();
		
		numFlagCastles = this.getGame().getPlayers().size() * NUM_FLAG_CASTLES_MULTIPLIER;
		
	}
	
	@Override
	public boolean isCompleted() {
		
		if (DEBUG)
			System.out.println("Checking is completed");
				
		// As this function is called every round,
		// let's check if we can set the flag castles
		if (flagCastles.isEmpty() && canCommenceDistribution()) {
			if (DEBUG)
				System.out.println("Distributing");
			distributeFlagCastles();
			return false;
		}
		
		return this.getWinner() != null;
	}

	@Override
	public Player getWinner() {
		
		Game game = this.getGame();
		
		if (game.getRound() < MIN_ROUND_FOR_WIN)
			return null;
		
		if (flagCastles.size() < 1)
			return null;
		
		return
		// Check if all flag castles belong
		// to exactly one player
		flagCastles.stream()
		    .map(x -> x.getOwner())
			.reduce(flagCastles.get(0).getOwner(), (x, y) -> {
				if (x == null || y == null)
					return null;
				else if (!x.equals(y))
					return null;
				else
					return x;
			});
				
	}

	@Override
	public boolean hasLost(Player player) {
		
		if (this.getGame().getRound() >= MIN_ROUND_FOR_WIN) {
			if (isCompleted())
				return player.equals(getWinner());
			return player.getNumRegions(getGame()) < 1;
		}
				
		return false;
		
	}
	
	/**
	 * Returns whether this castle is a flag castle
	 * @param castle The castle
	 * @return true if the castle is a flag castle, false otherwise
	 */
	public boolean isFlagCastle(Castle castle) {
		
		return flagCastles.contains(castle);
		
	}
	
	/**
	 * Distribute the flag castles evenly to
	 * all players
	 */
	private void distributeFlagCastles() {
		
		Game game = this.getGame();
		List<Player> players = game.getPlayers();
		
		int numCastlesToDistribute = 
		/*if*/	numFlagCastles < players.size() ?
		/*then*/		players.size() :
		/*else*/		numFlagCastles;
					
		for (int i = 0; i < players.size(); i++) {
			
			if (DEBUG)
				System.out.println("Distributing for " + players.get(i).getName());
			
			int playersLeft = players.size() - i;
			int numCastlesForPlayer = numCastlesToDistribute / playersLeft;
			
			if (numCastlesForPlayer > players.get(i).getCastles(game).size())
				numCastlesForPlayer = players.get(i).getCastles(game).size();
			
			pickRandomCastles(players.get(i).getCastles(game), numCastlesForPlayer)
				.stream()
				.forEach(x -> flagCastles.add(x));
			
			numCastlesToDistribute -= numCastlesForPlayer;
			
		}
		
	}
	
	/**
	 * Pick a number of random castles
	 * @param castles All castles
	 * @param num The number of castles to choose
	 * @return The picked castles
	 */
	private List<Castle> pickRandomCastles(List<Castle> castles, int num) {
		
		int min = 0;
		int max = castles.size() - 1;
		
		List<Integer> nums = new ArrayList<Integer>();
		
		if (num >= max)
			return new ArrayList<Castle>(castles);
		
		for (int i = 0; i < num; i++) {
			
			int newNum = newRandomInt(min, max);
			while (nums.contains(newNum))
				newNum = newRandomInt(min, max);
			nums.add(newNum);
			
		}
		
		if (DEBUG)
			System.out.println(nums);
		
		return nums.stream().map(x -> castles.get(x)).collect(Collectors.toList());
		
		
	}
	
	/**
	 * Returns whether the game is in a state ready for castle distribution
	 * @return
	 */
	private boolean canCommenceDistribution() {
		
		Game game = this.getGame();
		
		for (Castle castle : game.getMap().getCastles()) {
			if (castle.getOwner() == null)
				return false;
		}
		
		return true;
		
	}

}
