package jp.ac.nii.icpc2010.score;

import java.util.Vector;

import jp.ac.nii.icpc2010.Tron;
import jp.ac.nii.icpc2010.playfield.PlayField;

public class SurvivalScore extends AbstractScore {

	private double coinSum;
	private double rankSum;
	private Vector<Double> coins;
	private Vector<Double> ranks;

	public SurvivalScore(){
		this.coins = new Vector<Double>();
		this.ranks = new Vector<Double>();
	}

	@Override
	public void add(AbstractScore score) {
		this.coinSum += ((SurvivalScore)score).coinSum;
		this.rankSum += ((SurvivalScore)score).rankSum;
		this.coins.addAll(((SurvivalScore)score).coins);
		this.ranks.addAll(((SurvivalScore)score).ranks);
	}

	@Override
	public double getValue() {
		return coinSum + rankSum;
	}

	@Override
	public String toString() {
		return String.format("%.2f,%.2f", coinSum, rankSum);
	}

	@Override
	public int compareTo(AbstractScore o) {
		double m = 10e-8;
		double a = getValue();
		double b = ((SurvivalScore)o).getValue();
		if(a > b + m){
			return 1;
		}else if(a + m < b){
			return -1;
		}else{
			// TODO: use coins and ranks.
			return 0;
		}
	}

	public static AbstractScore[] getScores(PlayField playField){
		SurvivalScore[] scores = new SurvivalScore[playField.getNumOfPlayers()];

		int numOfPlayers = playField.getNumOfPlayers();
		int numOfCoins = playField.getNumOfCoins();
		for(int i = 0; i < numOfPlayers; i++){
			Tron tron = playField.getTron(i);

			scores[i] = new SurvivalScore();

			double coin = (numOfCoins > 0 ? tron.getCoins() / (double)numOfCoins : 0);
			scores[i].coinSum = coin;
			scores[i].coins.add(coin);

			int dead = 0;
			for(Tron t: playField.getTronsNocopy()){
				if(tron.getLifetime() > t.getLifetime()){
					dead++;
				}
			}
			double rank = (numOfPlayers > 1 ? dead / (playField.getNumOfPlayers() - 1.0) : 0);
			scores[i].rankSum = rank;
			scores[i].ranks.add(rank);
		}

		return scores;
	}
}
