package radargun.output.csv;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;

import radargun.comparsion.result.TestResult;

public class CSVExport {

	private final Path directory;

	public CSVExport(final Path directory) {
		this.directory = directory;
	}

	public Path export(final TestResult result) throws IOException {
		final String testName = result.getRunResult().getParams().getBenchmark();
		final double score = result.getRunResult().getPrimaryResult().getScore();
		final double lowerBound = result.getAssertion().getLowerBound();
		final double upperBound = result.getAssertion().getUpperBound();
		final Path csvFile = this.getOrCreateCSVFile(testName + ".csv");
		return this.appendResult(csvFile, score, lowerBound, upperBound);
	}

	private Path getOrCreateCSVFile(final String name) throws IOException {
		final Path csvFile = this.directory.resolve(name);
		if (Files.isRegularFile(csvFile)) {
			return csvFile;
		} else {
			return this.writeHeader(csvFile);
		}
	}

	private Path appendResult(final Path path, final double score, final double lowerBound, final double upperBound)
			throws IOException {
		return Files.write(path,
				('\n' + String.valueOf(score) + ',' + String.valueOf(lowerBound) + ',' + String.valueOf(upperBound))
						.getBytes(),
				StandardOpenOption.APPEND);
	}

	private Path writeHeader(final Path path) throws IOException {
		return Files.write(path, ("score,lowerBound,upperBound").getBytes(), StandardOpenOption.CREATE);
	}

}

@@ -925,36 +925,33 @@
 %7B%0D%0A%09%09final Path 
-csvF
+f
 ile = this.direc
@@ -997,20 +997,17 @@
 larFile(
-csvF
+f
 ile)) %7B%0D
@@ -1017,20 +1017,17 @@
 %09return 
-csvF
+f
 ile;%0D%0A%09%09
@@ -1055,24 +1055,23 @@
 his.
-writeHeader(csvF
+createCSVFile(f
 ile)
@@ -1122,20 +1122,20 @@
 al Path 
-path
+file
 , final 
@@ -1245,20 +1245,20 @@
 s.write(
-path
+file
 ,%0D%0A%09%09%09%09(
@@ -1435,19 +1435,21 @@
 ath 
-writeHeader
+createCSVFile
 (fin
@@ -1456,20 +1456,20 @@
 al Path 
-path
+file
 ) throws
@@ -1476,32 +1476,78 @@
  IOException %7B%0D%0A
+%09%09Files.createDirectories(file.getParent());%0D%0A
 %09%09return Files.w
@@ -1555,12 +1555,12 @@
 ite(
-path
+file
 , (%22

create csv export directory if not existing (fix #2)