import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;

class dataHandler {

    static void writeResult(String nameOfTest, Double data, String type, Integer threads, Integer duration, Integer size) throws Exception {

        File ResultsCSV = new File("ResultsCSV");
        if (! ResultsCSV.exists()){
            ResultsCSV.mkdir();
        }

        if (!type.equals("Latency") && !type.equals("Sample")){
            throw new Exception("Type must be either 'Latency' or 'Sample'");
        }

        File tempFile = new File("ResultsCSV/"
                + nameOfTest
                + "_Size-_"
                + size.toString()
                + ",_Threads-_"
                + threads.toString()
                + ",_Duration-_"
                + duration.toString()
				+ "_" + type
                + ".csv");
        boolean exists = tempFile.exists();
        try (FileWriter writer = new FileWriter(tempFile, true)) {

            DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime now = LocalDateTime.now();
            StringBuilder sb = new StringBuilder();

            if(type.equals("Latency")){

                if(!exists){
                    sb.append("date");
                    sb.append(",");
                    sb.append("latency");
                    sb.append('\n');
                }

                sb.append(dtf.format(now));
                sb.append(',');
                sb.append(data);
                sb.append('\n');


            } else {
                if(!exists){
                    sb.append("date");
                    sb.append(",");
                    sb.append("samples");
                    sb.append('\n');
                }

                sb.append(dtf.format(now));
                sb.append(',');
                sb.append(data);
                sb.append('\n');
            }

            writer.append(sb.toString());


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