package mior.view;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.PrintWriter;

import mior.model.IMiorModel;
import mior.model.IMiorUpdateListener;
import mior.model.MiorMM;
import mior.model.MiorOM;

public class MiorResultWriter implements IMiorUpdateListener {
	
	private int step;
	private PrintWriter output;
	private int lastCO2;
	private int CO2;
	
	private static final String SSEP = "\t";
	private static final String SEP = "\t\t";
	
	public MiorResultWriter(String outputPath) {
		try {
			output = new PrintWriter(new BufferedWriter(new FileWriter(outputPath)));
			output.println("#" + SSEP + "nbMM" + SSEP + "nbMMa" + SSEP + "CMM" + SEP + "COM" + SEP + "CO2" + SEP + "Total" + SEP + "dCO2");
		} catch (Exception e) {
			throw new RuntimeException("Invalid output file", e);
		}
	}
	
	@Override
	public void onMiorModelUpdated(IMiorModel model) {
		step++;
		
		int mmTotalActive = 0;
		int mmTotalCarbon = 0;
		int omTotalCarbon = 0;
		
		lastCO2 = Math.min(CO2, model.getWorld().CO2);
		CO2 = model.getWorld().CO2;
			
		for (MiorMM mm : model.getMMList()) {
			mmTotalCarbon += mm.getCarbone();
			if (mm.dormance == 0) {
				mmTotalActive ++;
			}
		}
		
		for (MiorOM om : model.getOMList()) {
			omTotalCarbon += om.getCarbone();
		}
		
		output.print(step);
		output.append(SSEP);
		
		output.print(model.getMMList().length);
		output.append(SSEP);
		
		output.print(mmTotalActive);
		output.append(SSEP);
		
		output.print(mmTotalCarbon);
		output.append(SEP);
		
		output.print(omTotalCarbon);
		output.append(SEP);
		
		output.print(CO2);
		output.append(SEP);
		
		output.print(mmTotalCarbon + omTotalCarbon + CO2);
		output.append(SEP);
		
		output.println(CO2 - lastCO2);
		output.flush();
	}	
	

}
