package be.iminds.ilabt.jfed.logging;

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;
import com.google.common.collect.EvictingQueue;
import com.google.common.collect.Queues;

import java.util.ArrayList;
import java.util.List;
import java.util.Queue;

/**
 * BugReportAppender
 */
public class BugReportAppender extends AppenderBase<ILoggingEvent> {
    public static final String DEFAULT_NAME = "BUGREPORT";
    private static final int MAX_SIZE = 2048;


    public interface LoggingEventListener {
        void onLoggingEvent(ILoggingEvent e);
    }

    private final Queue<ILoggingEvent> buffer;
    private final List<LoggingEventListener> listeners;

    {
        setName(DEFAULT_NAME);
    }

    public BugReportAppender() {
        buffer = Queues.synchronizedQueue(EvictingQueue.create(MAX_SIZE));
        listeners = new ArrayList<>();
    }

    @Override
    protected void append(ILoggingEvent e) {
        buffer.add(e);

        listeners.forEach(l -> l.onLoggingEvent(e));
    }

    public int getMaxSize() {
        return MAX_SIZE;
    }

    public synchronized List<ILoggingEvent> getListCopy() {
        return new ArrayList<>(buffer);
    }

    public int getLength() {
        return buffer.size();
    }

    public void addListeners(LoggingEventListener l) {
        listeners.add(l);
    }

    public void removeListeners(LoggingEventListener l) {
        listeners.remove(l);
    }
}
