package hiro.yoshioka.util.logging;

import org.apache.log4j.PatternLayout;
import org.apache.log4j.WriterAppender;
import org.apache.log4j.spi.LoggingEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.widgets.Display;

public class Log4JLoggingHandler extends AbsMyLoggingHandler {
	private static org.apache.log4j.Logger log4JLogger;
	MyAppender appender;
	private PatternLayout patternLayout;

	public Log4JLoggingHandler() {
		log4JLogger = org.apache.log4j.Logger.getRootLogger();
		log4JLogger.addAppender(new MyAppender());
	}

	@Override
	public void setLevel(String level) {
		log4JLogger.setLevel(org.apache.log4j.Level.toLevel(level));
	}

	@Override
	public String getLevel() {
		return log4JLogger.getLevel().toString();
	}

	class MyAppender extends WriterAppender {

		public void append(LoggingEvent loggingEvent) {
			if (styledText == null) {
				return;
			}
			if (this.layout == null) {
				patternLayout = new PatternLayout(
						"%d{HH:mm:ss} %5p %c{1} [%m]%n");
				this.layout = patternLayout;
			}

			final String message = this.layout.format(loggingEvent);

			String levelName = loggingEvent.getLevel().toString();

			if (!styledText.isDisposed()) {
				StyledTextData data = new StyledTextData(styledText,
						(Color) fColorMap.get(levelName + "_F"),
						(Color) fColorMap.get(levelName + "_B"), message);
				Display display = styledText.getDisplay();
				if (display.getThread() == Thread.currentThread()) {
					consoleWrite(data);
				} else {
					display.asyncExec(new StyledTextRunnable(data));
				}
			}
		}

	}
}