package org.xbib.logging.log4j.test;

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.logging.Formatter;

import org.xbib.logging.ExtHandler;
import org.xbib.logging.ExtLogRecord;
import org.xbib.logging.LogContext;
import org.xbib.logging.LogContextSelector;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;

public class AbstractTest {

    private static class TestLogContextSelector implements LogContextSelector {
        private final LogContext logContext;

        private TestLogContextSelector(final LogContext logContext) {
            this.logContext = logContext;
        }

        @Override
        public LogContext getLogContext() {
            return logContext;
        }
    }

    @BeforeEach
    public void logContextSetup() {
        LogContext.setLogContextSelector(new TestLogContextSelector(LogContext.create()));
    }

    @AfterEach
    public void resetLogContext() {
        LogContext.setLogContextSelector(LogContext.DEFAULT_LOG_CONTEXT_SELECTOR);
    }

    static class TestQueueHandler extends ExtHandler {
        private final Deque<ExtLogRecord> collected = new ArrayDeque<>();

        TestQueueHandler() {
        }

        TestQueueHandler(final Formatter formatter) {
            setFormatter(formatter);
        }

        @Override
        protected void doPublish(final ExtLogRecord record) {
            collected.addLast(record);
        }

        ExtLogRecord pollFirst() {
            return collected.pollFirst();
        }

        ExtLogRecord poll() {
            return collected.pollLast();
        }

        String pollFormatted() {
            return format(poll());
        }

        String pollFirstFormatted() {
            return format(pollFirst());
        }

        boolean isEmpty() {
            return collected.isEmpty();
        }

        private String format(final ExtLogRecord record) {
            if (record == null) {
                return null;
            }
            final Formatter formatter = getFormatter();
            if (formatter == null) {
                return record.getMessage();
            }
            return formatter.format(record);
        }
    }
}
