package uk.geekhole.foundations.utils;


import android.util.Log;

import com.google.common.io.Files;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.UUID;

import uk.geekhole.foundations.Global.App;

public class Util {
	private static final String APP_TAG = "Foundations";


	public static void log(String message) {
		log(message, null);
	}


	public static void log(String message, Throwable e) {
		Log.d(APP_TAG, message, e);
	}

	public static void atomicWrite(String filename, String data) {
		File temp = new File(App.getContext().getFilesDir(), filename);
		if (temp.exists()) {
			temp = new File(App.getContext().getFilesDir(), UUID.randomUUID().toString());
		}
		try {
			Files.write(data.getBytes(), temp);
			File finalFile = new File(filename);
			finalFile.delete();
			temp.renameTo(finalFile);
		} catch (IOException e) {
			Util.log("Write failed.", e);
		}
	}

	public static String read(String filePath) throws Exception {
		File fl = new File(App.getContext().getFilesDir(), filePath);
		FileInputStream fin = new FileInputStream(fl);
		String ret = convertStreamToString(fin);
		fin.close();
		return ret;
	}

	private static String convertStreamToString(InputStream is) throws Exception {
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuilder sb = new StringBuilder();
		String line;
		while ((line = reader.readLine()) != null) {
			sb.append(line).append("\n");
		}
		reader.close();
		return sb.toString();
	}

}
