package de.tud.kom.p2psim.impl.util;

import de.tud.kom.p2psim.api.common.SimHost;
import de.tud.kom.p2psim.impl.simengine.Simulator;
import de.tud.kom.p2psim.impl.vehicular.trafficlights.DefaultTrafficLightInformationComponent;
import de.tudarmstadt.maki.simonstrator.api.component.ComponentNotAvailableException;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import java.util.Map;

public class Summary {

    private static String csvOutputFilename = "";

    public static void simulationFinished() {
        Map<String, List<SimHost>> hosts = Simulator.getInstance().getScenario().getHosts();
        List<SimHost> simHostList = hosts.getOrDefault("TrafficLights", null);

        for (SimHost simHost : simHostList) {
            try {
                DefaultTrafficLightInformationComponent trafficLightInformationComponent = simHost.getComponent(DefaultTrafficLightInformationComponent.class);
                csvOutputFilename = simHost.getProperties().getProperty("csvOutputFile");
                writeToCSV(trafficLightInformationComponent.getTrafficLightId(), trafficLightInformationComponent.getNumberOfMessagesSent());
            } catch (ComponentNotAvailableException e) {
                e.printStackTrace();
            }
        }

    }

    private static void writeToCSV(String id, Double msgSent) {
        try {
            File file = new File(csvOutputFilename);
            String log = "";
            if (!file.exists()) {
                file.createNewFile();
                log += "id;messagesSent;\n";
            }

            FileWriter fileWriter = new FileWriter(file.getAbsoluteFile(), true);
            BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);

            log += id + ";" + String.valueOf(msgSent) + ";\n";
            bufferedWriter.write(log);
            bufferedWriter.close();

        } catch(IOException e) {
            e.printStackTrace();
        }
    }
}
