package jp.ac.nii.icpc2010.tournament;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Group {
	private boolean computed = false;
	private List<Player> players = new ArrayList<Player>();
	private Map<Player, List<Match>> player2matches = new HashMap<Player, List<Match>>();
	private List<Match> matches = new ArrayList<Match>();
	
	public void addPlayer(Player p) {
		players.add(p);
		player2matches.put(p, new ArrayList<Match>());
	}

	public List<Player> getPlayers() {
		return players;
	}
	
	public void addMatch(Match match) {
		matches.add(match);
		player2matches.get(match.getPlayerOne()).add(match);
		player2matches.get(match.getPlayerTwo()).add(match);
	}
	
	public List<Match> getMatches(Player p) {
		return player2matches.get(p);
	}
	
	public void flagComputed() {
		computed = true;
	}
	
	public void computeTotalScores() {
		for (Player one : players) {
			double totalScore = 0;
			for (Match match : getMatches(one)) {
				totalScore += match.getResult(one);
			}
			one.setScore(totalScore);
			Logger.log(one+"'s score: "+totalScore);
		}
	}
	
	public List<Player> getProceedingPlayers() {
		if (!computed) return players;
		
		Collections.sort(players);
		List<Player> proceedingPlayers = new ArrayList<Player>();
		for (int x = 0; x < 2; x++) {
			proceedingPlayers.add(players.get(players.size()-1-x));
		}
		return proceedingPlayers;
	}
	
	@Override
	public String toString() {
		String res = "";
		for (Player p : players) {
			res += p + " ";
		}
		return res;
	}
}
