package com.sttcare.alarmSwitch;

/*
 // ändra java build path (projects) att även inkludera systemwatch-projektet

 // import
 import com.sttcare.alarmSwitch.systemWatch.ErrorLogger;


 // init

 ErrorLogger errLogger = new ErrorLogger(logger);

 // log

 logger.info("lite infolog...");
 errLogger.info();
 logger.fatal("Out of sockets! Many problems, oh no no no...catastrophe!");
 errLogger.fatal();


 // kill

 errLogger = null;
 */

import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Enumeration;
import java.util.LinkedList;

import org.apache.log4j.Appender;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.WriterAppender;
import org.apache.log4j.RollingFileAppender;
import org.apache.log4j.Level;
import org.apache.log4j.SimpleLayout;
import org.apache.log4j.FileAppender;

public class ErrorLogger {

	// static stuff, same for all objects
	private static Logger errorLogger = null;

	// object stuff
	private StringWriter sw = null;
	private Logger privateLogger = null;

	LinkedList<String> historyList;

	int maxHistorySize;
	String[] strArray;
	int nextFreePos;
	int usedSize;

	
	// Create the errorlogger. It's logging to a private file.
	public static void initErrorLogger() throws IOException {
		if (errorLogger == null) {
			// skapa och sätt upp errorLoggern
			errorLogger = Logger.getLogger(ErrorLogger.class);

			SimpleLayout layout = new SimpleLayout();

			RollingFileAppender writer = null;
			FileAppender appender = null;
			try {
				writer = new RollingFileAppender(layout,
						"/var/log/sttlogs/error.log");

				writer.setMaxBackupIndex(5);
				writer.setMaximumFileSize(1024 * 1024);

				errorLogger.addAppender(writer);
				errorLogger.setLevel((Level) Level.DEBUG);
			} catch (Exception e) {

			}

		}

	}

	public ErrorLogger(Logger paramPrivateLogger) throws IOException {

		initErrorLogger();

		// we're spying on this logger
		privateLogger = paramPrivateLogger;

		sw = new StringWriter(500);
		String pattern = "%d{yyMMdd HHmmss} %-5p %C{1}.%M:%L %m%n";
		PatternLayout errorLayout = new PatternLayout(pattern);
		WriterAppender writer = new WriterAppender(errorLayout, sw);
		
		// here we're attaching another appender, which does the spying for us
		privateLogger.addAppender(writer);

		maxHistorySize = 8;
		initHistoryBuffer(maxHistorySize);
	}

	public void fatal() {
		// then read the StringWriter and get the outputstring we now got,
		// through spying.
		String newMessage = sw.toString();

		// Set the size to 0, so it will not keep any data.
		sw.getBuffer().setLength(0);

		// add it to our rolling queue of history-strings
		addHistoryMessage(newMessage);

		// output the entire history of Strings to the errorLogger
		printHistoryToErrorLog();
	}

	public void error() {
		// then read the StringWriter and get the outputstring we now got,
		// through spying.
		String newMessage = sw.toString();

		// Set the size to 0, so it will not keep any data.
		sw.getBuffer().setLength(0);

		// add it to our rolling queue of history-strings
		addHistoryMessage(newMessage);

		// output the entire history of Strings to the errorLogger
		printHistoryToErrorLog();
	}

	public void warn() {
		// then read the StringWriter and get the outputstring we now got,
		// through spying.
		String newMessage = sw.toString();

		// Set the size to 0, so it will not keep any data.
		sw.getBuffer().setLength(0);

		// add it to our rolling queue of history-strings
		addHistoryMessage(newMessage);

		// output the entire history of Strings to the errorLogger
		printHistoryToErrorLog();
	}

	public void info() {
		// then read the StringWriter and get the outputstring we now got,
		// through spying.
		String newMessage = sw.toString();
		sw.getBuffer().setLength(0);

		// add it to our rolling queue of history-strings
		addHistoryMessage(newMessage);
	}

	public void debug() {
		// then read the StringWriter and get the outputstring we now got,
		// through spying.
		String newMessage = sw.toString();
		sw.getBuffer().setLength(0);

		// add it to our rolling queue of history-strings
		addHistoryMessage(newMessage);
	}

	private void initHistoryBuffer(int sizeOfHistory) {
		strArray = new String[sizeOfHistory];
		nextFreePos = 0;
		usedSize = 0;

		historyList = new LinkedList<String>();
	}

	private void addHistoryMessage(String newMessage) {
		
		// had problems with logging being in a mess without newlines, not sure how this happens
		// only sometimes, on just one row! Must be another problem...
		
		boolean foundNewLine = false;
		char ch = 0x0a;
		if (newMessage.indexOf(ch) != -1) {
			foundNewLine = true;
		}
		ch = 0x0d;
		if (newMessage.indexOf(ch) != -1) {
			foundNewLine = true;
		}
		if (newMessage.endsWith("\n")) {
			foundNewLine = true;
		}
		if (newMessage.endsWith("\r")) {
			foundNewLine = true;
		}

		if (foundNewLine == false)
			newMessage += "\r\n";

		historyList.addLast(newMessage);
		if (historyList.size() >= maxHistorySize) {
			historyList.removeFirst();
		}
	}

	private void printHistoryToErrorLog() {
		errorLogger.info("*************** HISTORY LISTING ***************");
		// errorLogger.info("size:"+historyList.size());
		int i = 0;
		for (String s : historyList) {
			errorLogger.info(s);
			i++;
		}
		errorLogger.info("              ");

		historyList.clear();
	}

}
