package game.goals;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

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

public class TimeGoal extends Goal {

	int maxRounds;
	
	public TimeGoal() {
		this(4);
	}
	
	public TimeGoal(int maxRounds) {
		super("Countdown", "Derjenige Spieler gewinnt, der nach " + maxRounds + " Runden die meisten Burgen besitzt.");
		this.maxRounds = maxRounds;
	}
	
	@Override
	public boolean isCompleted() {
		return this.getWinner() != null;
	}

	@Override
	public Player getWinner() {
		
		Game game = this.getGame();
		
		// If a player conquers all castles before the time limit is over, the game should obviously end there.
		if(game.getRound() < maxRounds) {
			
			// Copy-pasted from ConquerGoal.java
	        if(game.getRound() < 2)
	            return null;

	        Player p = null;
	        for(Castle c : game.getMap().getCastles()) {
	            if(c.getOwner() == null)
	                return null;
	            else if(p == null)
	                p = c.getOwner();
	            else if(p != c.getOwner())
	                return null;
	        }

	        return p;
		}
		
		List<Player> playerList = game.getPlayers();
		Comparator<Player> comp = new Comparator<Player>() {
			
			public int compare(Player p1, Player p2) {
				
				return Integer.compare(p1.getNumRegions(game), p2.getNumRegions(game));
				
			}
			
		};
		System.out.println(Collections.max(playerList, comp).getNumRegions(game));
		System.out.println(Collections.max(playerList, comp).getName());
		return Collections.max(playerList, comp);
	}

	@Override
	public boolean hasLost(Player player) {
		
		if(getGame().getRound() < maxRounds)
	            return false;

	    return !player.equals(getWinner());
	}
}
