package org.xbib.logging.test;

import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.xbib.logging.Level;
import org.xbib.logging.LogManager;
import org.xbib.logging.Logger;

public class LogManagerTests extends AbstractTest {

    static {
        // Access a logger in initialize the logmanager
        java.util.logging.Logger.getAnonymousLogger();
    }

    private final java.util.logging.Level[] levels = {
            Level.TRACE,
            Level.DEBUG,
            Level.INFO,
            Level.WARN,
            Level.ERROR,
            Level.FATAL,
            java.util.logging.Level.ALL,
            java.util.logging.Level.FINEST,
            java.util.logging.Level.FINER,
            java.util.logging.Level.FINE,
            java.util.logging.Level.INFO,
            java.util.logging.Level.CONFIG,
            java.util.logging.Level.WARNING,
            java.util.logging.Level.SEVERE,
            java.util.logging.Level.OFF,
    };

    public LogManagerTests() {
    }

    @Test
    public void testLevelReplacement() throws Exception {
        // Validate each level
        for (java.util.logging.Level l : levels) {
            java.util.logging.Level level = java.util.logging.Level.parse(l.getName());
            Assertions.assertEquals(l, level);
            level = java.util.logging.Level.parse(Integer.toString(l.intValue()));
            Assertions.assertEquals(l, level);
        }
    }

    @Test
    public void checkLoggerNames() {
        // Get the log manager
        final java.util.logging.LogManager logManager = java.util.logging.LogManager.getLogManager();
        // Should be a org.xbib.logging.LogManager
        Assertions.assertEquals(LogManager.class, logManager.getClass());

        final List<String> expectedNames = Arrays.asList("", "test1", "org.xbib", "org.xbib.logging", "other", "stdout");

        // Create the loggers
        for (String name : expectedNames) {
            Logger.getLogger(name);
        }
        compare(expectedNames, Collections.list(logManager.getLoggerNames()));
    }

    private <T> void compare(final Collection<T> expected, final Collection<T> actual) {
        Assertions.assertTrue(expected.containsAll(actual), () -> "Expected: " + expected + " Actual: " + actual);
        Assertions.assertTrue(actual.containsAll(expected), () -> "Expected: " + expected + " Actual: " + actual);
    }
}
