package edu.oregonstate.cope.clientRecorder;

import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Calendar;

/**
 * Class responsible with file persistence policy: <br>
 * <ul>
 * <li>Writing to files</li>
 * <li>Where to store files. Location should be set at startup</li>
 * <li>When to switch to a new file</li>
 * <li>File naming policy</li>
 * </ul>
 */
public class FileManager {

	private String rootDirectory;
	
	public FileManager() {
		setRootDirectory("outputFiles");
	}

	public void setRootDirectory(String rootDirectory) {
		this.rootDirectory = rootDirectory;
		
		try {
			Files.createDirectories(Paths.get(rootDirectory));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void write(String string) {
		try {
			Files.write(getFilePath(), string.getBytes(), StandardOpenOption.CREATE, StandardOpenOption.APPEND);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public boolean isCurrentFileEmpty() {
		try {
			return getFilePath().toFile().length() == 0;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}

	public void deleteFiles() throws IOException {
		DirectoryStream<Path> directoryStream = Files.newDirectoryStream(Paths.get(rootDirectory));

		for (Path path : directoryStream) {
			Files.delete(path);
		}
	}

	protected Path getFilePath() throws IOException {
		Path filePath = Paths.get(rootDirectory, getFileName());

		return filePath;
	}

	protected String getFileName() {
		Calendar cal = Calendar.getInstance();
		String pathName = cal.get(Calendar.YEAR) + "-" + cal.get(Calendar.MONTH) + "-" + cal.get(Calendar.DAY_OF_MONTH);

		return pathName;
	}
}

@@ -544,22 +544,20 @@
 private 
-String
+Path
  rootDir
@@ -706,16 +706,26 @@
 ctory = 
+Paths.get(
 rootDire
@@ -729,16 +729,34 @@
 irectory
+).toAbsolutePath()
 ;%0A%09%09%0A%09%09t
@@ -787,26 +787,21 @@
 ctories(
-Pa
 th
+i
 s.
-get(
 rootDire
@@ -806,17 +806,16 @@
 rectory)
-)
 ;%0A%09%09%7D ca
@@ -1476,26 +1476,16 @@
 yStream(
-Paths.get(
 rootDire
@@ -1490,17 +1490,16 @@
 rectory)
-)
 ;%0A%0A%09%09for
@@ -1619,34 +1619,15 @@
 %7B%0A%09%09
-Path filePath = Paths.get(
+return 
 root
@@ -1635,18 +1635,25 @@
 irectory
-, 
+.resolve(
 getFileN
@@ -1663,28 +1663,8 @@
 ());
-%0A%0A%09%09return filePath;
 %0A%09%7D%0A

change type of rootDirectory to Path