package de.wwwu.awolf.presenter.util;

import de.wwwu.awolf.presenter.Presenter;
import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.spi.LoggingEvent;
import org.powermock.core.classloader.annotations.PowerMockIgnore;

@PowerMockIgnore("org.apache.log4j.Appender")
public class GuiAppender extends AppenderSkeleton {

    private Presenter presenter;

    public GuiAppender() {
        super();

        Presenter tmpInstance = Presenter.getInstance();
        while (tmpInstance == null) {
            try {
                Thread.sleep(1000);
                tmpInstance = Presenter.getInstance();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        presenter = Presenter.getInstance();
    }

    public GuiAppender(boolean isActive) {
        super(isActive);
    }

    /**
     * [DEBUG] 2020-03-27 23:58:40 [Thread-3] - View has been set.
     *
     *
     * @param logEvent
     */
    @Override
    protected void append(LoggingEvent logEvent) {
        if (presenter != null && presenter.getView() != null) {
            presenter.getView().logInfo("[" + logEvent.getLevel() + "] " + logEvent.getThreadName() + ": " + logEvent.getRenderedMessage());
        }
    }

    @Override
    public void close() {

    }

    @Override
    public boolean requiresLayout() {
        return true;
    }

}
