import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;

import Six.Sixp.Client.*;

public class MyLogger implements IClientLogging {

	private FileOutputStream sw;
	private PrintStream ps;
	private Boolean isOpen;
	
	public MyLogger(String workDir){
		String logFile = workDir + "demo.log";
		try {
			sw = new FileOutputStream(logFile);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			System.out.println("Cannot create log file!");
		}
		isOpen = true;
	}
	
	@Override
	public void OnLogMessage(LogLevel level, String text) {
		synchronized(sw) {
			System.out.println("L " + level + ": " + text);
			try {
				ps = new PrintStream(sw);
				ps.println(text + "\n");
				ps.close();
				sw.flush();
			} catch (IOException e) {
				e.printStackTrace();
				System.out.println("OnLogMessage failed to write to file!");
			}
		}
	}
	
	@Override
	public void OnLogMessage(LogLevel level, String text, Exception ex) {
		synchronized(sw) {
			System.out.println("L " + level + ": " + text + "Ex:" + ex.getMessage());
			try {
				ps = new PrintStream(sw);
				ps.println(text + " Ex:" + ex.getMessage() + "\n");
				ps.close();
				sw.flush();
			} catch (IOException e) {
				e.printStackTrace();
				System.out.println("OnLogMessage with exception failed to write to file!");
			}
		}		
	}

	@Override
	public boolean getIsDebugLoggingEnabled() {
		return false;
	}
	
	public void Dispose() {
		Deinit();
	}
	
	private void Deinit() {
		if (!isOpen) return;
		try {
			sw.close();
		} catch (IOException e) {
			e.printStackTrace();
			System.out.println("Could not close log file!");
		}
		isOpen = false;
	}
	
	protected void finalize() {
		Deinit();
	}
}
