package at.ac.tuwien.lsdc.util;

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

import at.ac.tuwien.lsdc.types.ScenarioData;
import at.ac.tuwien.lsdc.types.SchedulerData;

public class CSVLogger {

	private File file;

	public CSVLogger(File file) throws IOException {
		this.file = file;
	}

	public void logScenarioData(ScenarioData data) throws IOException {
		if (file.length() == 0) {
			writeScenarioDataHeader();
		}
		writeCSVLine(data.toStringArray());
	}

	public void logSchedulerData(SchedulerData data) throws IOException {
		if (file.length() == 0) {
			writeSchedulerDataHeader();
		}
		writeCSVLine(data.toStringArray());
	}

	private void writeScenarioDataHeader() throws IOException {
		String[] header = new String[] { "Scheduler", "Scenario", "TotalPMs", "TotalVMs",
				"TotalDuration", "TotalPowerConsumption", "TotalInSourced", "TotalOutSourced",
				"TotalResizeEvents", "TotalDelayedApps", "TotalStarted", "TotalStopped"};
		writeCSVLine(header);
	}

	private void writeSchedulerDataHeader() throws IOException {
		String[] header = new String[] { "Timestamp", "TotalRAM", "TotalCPU", "TotalSize",
				"RunningPMs", "RunningVMs", "TotalPowerConsumption", "InSourced", "OutSourced",
				"TotalResizes", "DelayedApps", "Started", "Stopped"};
		writeCSVLine(header);
	}

	private void writeCSVLine(String[] arr) throws IOException {
		PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file, true)));
		StringBuilder csvBuilder = new StringBuilder();

		for (String s : arr) {
			csvBuilder.append(s).append(";");
		}

		csvBuilder.deleteCharAt(csvBuilder.length() - 1);
		out.println(csvBuilder.toString());
		out.close();
	}

}
