package jp.hasc.hasctool.ui;

import java.io.IOException;
import java.io.Writer;

import org.apache.log4j.Level;
import org.apache.log4j.WriterAppender;
import org.apache.log4j.spi.LoggingEvent;
import org.apache.log4j.spi.ThrowableInformation;
import org.eclipse.core.runtime.ILog;
import org.eclipse.core.runtime.Status;
import org.eclipse.ui.console.ConsolePlugin;
import org.eclipse.ui.console.IConsole;
import org.eclipse.ui.console.IConsoleManager;
import org.eclipse.ui.console.MessageConsole;
import org.eclipse.ui.console.MessageConsoleStream;

/**
 * Eclipseのconsoleに出力する、log4jのAppenderです
 * @author iwasaki
 */
public class EclipseConsoleAppender extends WriterAppender {
	private ILog log_;

	public void activateOptions() {
		MessageConsole console=new MessageConsole("HascTool", null);
		IConsoleManager consoleManger = ConsolePlugin.getDefault().getConsoleManager();
		consoleManger.addConsoles(new IConsole[]{console});
		final MessageConsoleStream consoleStream=console.newMessageStream();
		log_ = Activator.getDefault().getLog();
		setWriter(new Writer() {
			@Override
			public void write(char[] cbuf, int off, int len) throws IOException {
				String s=new String(cbuf,off,len);
				consoleStream.print(s);
			}
			
			@Override
			public void flush() throws IOException {
				consoleStream.flush();
			}
			
			@Override
			public void close() throws IOException {
				consoleStream.close();
			}
		});
		//
		super.activateOptions();
	}

	@Override
	protected void subAppend(LoggingEvent event) {
		if (event.getLevel().isGreaterOrEqual(Level.WARN)) {
			// ErrorLog Viewにも出す
			Throwable th=null;
			ThrowableInformation thi = event.getThrowableInformation();
			if (thi!=null) {
				th = thi.getThrowable();
			}
			log_.log(new Status(event.getLevel().isGreaterOrEqual(Level.ERROR)?Status.ERROR:Status.WARNING,
					Activator.PLUGIN_ID, event.getMessage().toString(),th));
		}
		//
		super.subAppend(event);
	}
}
