package inc.monsters.mias.data.statistics;

import inc.monsters.mias.data.Kid;
import inc.monsters.mias.data.facade.KidService;

import java.awt.Color;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import org.apache.myfaces.trinidad.model.ChartModel;

public class AgeVsBraveness extends ChartModel {
	private static final Logger log = Logger.getLogger("inc.monsters.mias");

	private KidService kidService;

	private List<List<Double>> data;
	private List<Kid> kids;

	public KidService getKidService() {
		return kidService;
	}

	public void setKidService(KidService kidService) {
		this.kidService = kidService;
	}

	public List<Kid> getKids() {
		if(null == kids) {
			kids = kidService.getKids();
		}
		return kids;
	}

	private void calculate() {
		log.fine("calculate()");
		if(null == data || 0 == data.size()) {
			data = new ArrayList<List<Double>>();
			
			// We know the maximum age is 11, so add 12 lists
			for(int i = 0; i < 12; i++) {
				data.add(new ArrayList<Double>());
				data.get(i).add(0.0);
			}
			
			for(Kid kid: getKids()) {
				int age = kid.getAge();
				double braveness = kid.getBraveness();
				
				double oldValue = data.get(age).get(0);
				double newValue;
				if (0.0 == oldValue) {
					newValue = braveness;
				} else {
					newValue = (oldValue + braveness) / 2.0;
				}
				
				data.get(age).set(0, newValue);
			}
	
			log.fine("bravenessData size: " + data.size());
			for(List<Double> list : data) {
				log.finer(" => " + list);
			}
		}
	}
	
	@Override
	public List<String> getGroupLabels() {
		log.fine("getGroupLabels()");
		calculate();
		List<String> x = new ArrayList<String>();
		for(int i = 0; i < data.size(); i++) {
			x.add("" + i);
		}
		return x;
	}

	@Override
	public List<String> getSeriesLabels() {
		log.fine("getSeriesLabels()");
		calculate();
		List<String> x = new ArrayList<String>();
		x.add("Braveness");
		return x;
	}

	@Override
	public List<List<Double>> getYValues() {
		log.fine("getYValues()");
		calculate();
		return data;
	}

	@Override
	public String getFootNote() {
		return super.getFootNote();
	}

	@Override
	public Double getMaxXValue() {
		return super.getMaxXValue();
	}

	@Override
	public Double getMaxYValue() {
		return super.getMaxYValue();
	}

	@Override
	public Double getMinXValue() {
		return super.getMinXValue();
	}

	@Override
	public Double getMinYValue() {
		return super.getMinYValue();
	}

	@Override
	public List<Color> getSeriesColors() {
		return super.getSeriesColors();
	}

	@Override
	public String getSubTitle() {
		return super.getSubTitle();
	}

	@Override
	public String getTitle() {
		return "Age versus Braveness";
	}

	@Override
	public List<List<Double>> getXValues() {
		return super.getXValues();
	}
}