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

/**
 * Class for storing debate scores for a collection of candidates.
 *   @author Dave Reed
 *   @version 1/22/16
 */
public class DebateScorer {
    private HashMap<String, Candidate> scores;

    /**
     * Constructs an empty DebateScorer.
     */
    public DebateScorer() {
        this.scores = new HashMap<String, Candidate>();
    }

    /**
     * Records a single score for a particular candidate.
     *   @param name the name of the candidate
     *   @param score the score for that candidate
     */
    public void recordRating(String name, double score) {
        if (!this.scores.containsKey(name)) {
            this.scores.put(name, new Candidate(name));
        }
    	this.scores.get(name).record(score);        
    }
    
    /**
     * Calculates the average score over all the candidates.
     *   @return the average candidate score
     */
    public double getAverage() {
        double total = 0.0;
        int num = 0;
        for (Candidate c : this.scores.values()) {
            total += c.getTotal();
            num++;
        }
        if (num > 0) {
            return total/num;
        }
        return 0.0;
    }
    
    /**
     * Calculates the total number of positive scores recorded.
     *   @return the number of positives
     */
    public int getPositives() {
        int num = 0;
        for (Candidate c : this.scores.values()) {
            num += c.getPositive();
        }
        return num;       
    }

    /**
     * Calculates the total number of negative scores recorded.
     *   @return the number of negatives
     */
    public int getNegatives() {
        int num = 0;
        for (Candidate c : this.scores.values()) {
            num += c.getNegative();
        }
        return num;       
    }
    
    /**
     * Converts the debate scoring info into a String.
     *   @return the String representation
     */
    public String toString() {
        ArrayList<Candidate> sorted = new ArrayList<Candidate>();
        for (Candidate c : this.scores.values()) {
            sorted.add(c);
        }
        Collections.sort(sorted);
        
        String message = String.format("%-10s %8s %8s %8s",
                             "CANDIDATE", "TOTAL", "# POS", "# NEG");
        for (Candidate c : sorted) {
            message += "\n" + c.toString();
        }
        message += "\n-------------------------------------\n";
        message += String.format("%-10s %8.1f %8d %8d",
                             "", this.getAverage(), this.getPositives(), 
                             this.getNegatives());
        return message;
    } 
}

