package scoring;
import java.util.List;

/**
 * Calculate the average Score from a List of Score objects.
 * 
 * @author  Farley B. Adkoter, perspecTV
 * @version 1.0
 */
public class AverageSystem implements ScoringSystem
{
	private boolean shouldIgnoreMissing;

	/**
	 * Default Constructor (i.e., construct an AverageSystem that does not
	 * ignore missing values).
	 */
	public AverageSystem()
	{
		this(true);
	}

	/**
	 * Explicit Value Constructor.
	 * 
	 * @param shouldIgnoreMissing   true if this ScoringSystem should ignore missing values
	 */
	public AverageSystem(boolean shouldIgnoreMissing)
	{
		shouldIgnoreMissing = shouldIgnoreMissing;
	}
	
	/**
	 * Calculate the (in this case, average) Score from a List of Score objects. 
	 * 
	 * 
	 * @param key    The key to use for the resulting Score
	 * @param scores The List of Score objects to use in the calculation
	 * @return       The resulting Score
	 * @throws SizeException If scores is null or of size 0
	 */
	public Score calculate(String key, List<Score> scores) throws SizeException
	{	
		// Early Error Checking
		if (scores.size() == 0) throw new SizeException("No Scores");
		
		double  total = 0.0;
		int     count = -1;
		
		for (Score s: scores)
		{
			Double current = s.getValue();
			
			if ((current != null) && (shouldIgnoreMissing))
			{
				total += current.doubleValue();
				++count;
			}
			else
			{
				total += Missing.doubleValue(current);
				++count;
			}
		}
		
		// Late Error Checking
		if (count == 0) throw new IllegalArgumentException("All Scores Have Missing Values");
		
		return new LeafScore(key, total/count);
	}
	
}
