package singleton.lazyLogger;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;

public class Logger {

	private static String singletonType = "LAZY";
	private static Logger uniqueInstance;
	public static final String DIRECTORY = "C:\\temp\\";
	private String fileName;

	/*
	 * Note that the constructor is private
	 */
	private Logger() { 
		Calendar cal = new GregorianCalendar();
		SimpleDateFormat sdfAbbrev = new SimpleDateFormat("yyyy-MMM-dd");
		SimpleDateFormat sdfFull = new SimpleDateFormat("yyyy-MMM-dd kk:mm:ss");
		this.fileName = DIRECTORY + 
				sdfAbbrev.format(cal.getTime()) + 
				"_" + getSingletonType() + "_activity_log.txt";
		try {
			/* Does file exist?
			 *      Note: must check for file existence before the buffered writer
			 *      creates it.
			 */
			File logFile = new File(this.fileName);
			boolean logExists = logFile.exists();
			
			BufferedWriter writer = new BufferedWriter(
					new FileWriter(this.fileName, true)); //  mode
			if (!logExists) writer.write(sdfFull.format(cal.getTime()) + " Log created.");
			writer.newLine();
			writer.close();
		}
		catch (IOException e) {
			e.printStackTrace();
		}
	}

	/** 
	 * This method will create the unique logger LAZILY.
	 * A logger will only be created if someone asks for
	 * it by calling this method.
	 */
	public static Logger getInstance() {
		if (uniqueInstance == null) {
			uniqueInstance = new Logger();
		}
		return uniqueInstance;
	}

	public void logMessage(String message) {

		Calendar cal = new GregorianCalendar();
		SimpleDateFormat sdfFull = new SimpleDateFormat("yyyy-MMM-dd kk:mm:ss");
		try {
			BufferedWriter writer = new BufferedWriter(
					new FileWriter(this.fileName, true)); // append mode
			writer.write(sdfFull.format(cal.getTime()) + " " + message);
			writer.newLine();
			writer.close();
		}
		catch (IOException e) {
			e.printStackTrace();
		}
	}

	public String getFileName() {
		return fileName;
	}

	public static String getSingletonType() {
		return singletonType;
	}
	
}

