package de.heatup.logging;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;

public class Logger {
	private static boolean logging = false;
	private static boolean firstWrite = true;
	private static boolean toCmd = true;
	private static boolean toFile = false;
	private static String logFile;

	/*
	 * writes a new log line to commandline/shell via System.out.println() and/or (if enabled) appends a new line to a log file
	 */
	@SuppressWarnings("resource")
	public static void write(String s) {
		if (logging) {
			if (toCmd) {
				System.out.println(s);
			}
			if (toFile) {
				PrintStream out;
				try {
					if (firstWrite) {
						out = new PrintStream(new FileOutputStream(logFile));
						firstWrite = false;
					} else {
						out = new PrintStream(new FileOutputStream(logFile, true));
					}
				} catch (FileNotFoundException e) {
					File f = new File(logFile);
					try {
						f.createNewFile();
						if (firstWrite) {
							out = new PrintStream(new FileOutputStream(logFile));
							firstWrite = false;
						} else {
							out = new PrintStream(new FileOutputStream(logFile, true));
						}
					} catch (IOException e1) {
						out = null;
						e1.printStackTrace();
					}
				}
				out.println(s);
				out.close();
			}
		}
	}
	/*
	 * sets the log file to given logFile.
	 * logFile can include a path.
	 */
	public static void setLogFile(String logFile) {
		Logger.toFile = true;
		Logger.logFile = logFile;
	}
	/*
	 * prints the name (and path if given)
	 */
	public static String getLogFile() {
		return Logger.logFile;
	}
	/*
	 * enables logging
	 * logging is enabled by default
	 */
	public static void enableLogging() {
		Logger.logging = true;
	}
	/*
	 * disables logging until reenabled with enableLogging()
	 */
	public static void disableLogging() {
		Logger.logging = false;
	}
	/*
	 * disables System.out.println() logging
	 */
	public static void disableCmdLogging() {
		Logger.toCmd = false;
	}
	/*
	 * enables System.out.println() logging
	 */
	public static void enableCmdLogging() {
		Logger.toCmd = true;
	}
}
