package org.xbib.logging.test;

import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Handler;
import java.util.logging.LogRecord;

import org.xbib.logging.ExtHandler;
import org.xbib.logging.ExtLogRecord;
import org.xbib.logging.Level;
import org.xbib.logging.LogContextInitializer;
import org.xbib.logging.Logger;
import org.xbib.logging.LoggerNode;
import org.xbib.logging.filters.RegexFilter;
import org.junit.jupiter.api.Test;
import org.xbib.logging.formatters.DefaultFormatter;

public final class LoggerTests {

    public LoggerTests() {
    }

    @Test
    public void testInstall() {
        assertTrue((java.util.logging.Logger.getLogger("test") instanceof Logger), "Wrong logger class");
    }

    @Test
    public void testSafeClone() {
        assertSame(LogContextInitializer.NO_HANDLERS, LoggerNode.safeCloneHandlers());
        assertSame(LogContextInitializer.NO_HANDLERS, LoggerNode.safeCloneHandlers((Handler) null));
        assertSame(LogContextInitializer.NO_HANDLERS, LoggerNode.safeCloneHandlers(null, null));

        Handler h1 = new NullHandler();
        Handler h2 = new NullHandler();
        assertArrayEquals(new Handler[] { h1, h2 }, LoggerNode.safeCloneHandlers(h1, h2));
        assertArrayEquals(new Handler[] { h1, h2 }, LoggerNode.safeCloneHandlers(h1, h2, null));
        assertArrayEquals(new Handler[] { h1, h2 }, LoggerNode.safeCloneHandlers(h1, null, h2));
        assertArrayEquals(new Handler[] { h1, h2 }, LoggerNode.safeCloneHandlers(null, h1, h2));
        assertArrayEquals(new Handler[] { h1, h2 }, LoggerNode.safeCloneHandlers(null, h1, null, h2, null));

        assertArrayEquals(new Handler[] { h1 }, LoggerNode.safeCloneHandlers(null, h1));
        assertArrayEquals(new Handler[] { h1 }, LoggerNode.safeCloneHandlers(h1, null));
    }

    @Test
    public void testCategories() {
        assertNotNull(Logger.getLogger(LoggerTests.class.getName()),
                "Logger not created with category: " + LoggerTests.class.getName());
        assertNotNull(Logger.getLogger("Spaced Logger Name"), "Logger not created with category: Spaced Logger Name");
        assertNotNull(Logger.getLogger("/../Weird/Path"), "Logger not created with category: /../Weird/Path");
        assertNotNull(Logger.getLogger("random.chars.`~!@#$%^&*()-=_+[]{}\\|;':\",.<>/?"),
                "Logger not created with category: random.chars.`~!@#$%^&*()-=_+[]{}\\|;':\",.<>/?");
    }

    @Test
    public void testHandlerAdd() {
        final NullHandler h1 = new NullHandler();
        final NullHandler h2 = new NullHandler();
        final NullHandler h3 = new NullHandler();
        final Logger logger = Logger.getLogger("testHandlerAdd");
        logger.addHandler(h1);
        logger.addHandler(h2);
        logger.addHandler(h3);
        boolean f1 = false;
        boolean f2 = false;
        boolean f3 = false;
        for (Handler handler : logger.getHandlers()) {
            if (handler == h1)
                f1 = true;
            if (handler == h2)
                f2 = true;
            if (handler == h3)
                f3 = true;
        }
        assertTrue(f1, "Handler 1 missing");
        assertTrue(f2, "Handler 2 missing");
        assertTrue(f3, "Handler 3 missing");
    }

    @Test
    public void testHandlerAdd2() {
        final NullHandler h1 = new NullHandler();
        final Logger logger = Logger.getLogger("testHandlerAdd2");
        logger.addHandler(h1);
        logger.addHandler(h1);
        logger.addHandler(h1);
        boolean f1 = false;
        final Handler[] handlers = logger.getHandlers();
        for (Handler handler : handlers) {
            if (handler == h1) {
                f1 = true;
            }
        }
        assertTrue(f1, "Handler 1 missing");
        assertEquals(3, handlers.length, "Extra handlers missing");
    }

    @Test
    public void testHandlerRemove() {
        final NullHandler h1 = new NullHandler();
        final NullHandler h2 = new NullHandler();
        final NullHandler h3 = new NullHandler();
        final Logger logger = Logger.getLogger("testHandlerRemove");
        logger.addHandler(h1);
        logger.addHandler(h2);
        logger.addHandler(h3);
        logger.removeHandler(h1);
        boolean f1 = false;
        boolean f2 = false;
        boolean f3 = false;
        for (Handler handler : logger.getHandlers()) {
            if (handler == h1)
                f1 = true;
            if (handler == h2)
                f2 = true;
            if (handler == h3)
                f3 = true;
        }
        assertFalse(f1, "Handler 1 wasn't removed");
        assertTrue(f2, "Handler 2 missing");
        assertTrue(f3, "Handler 3 missing");
    }

    @Test
    public void testHandlerRemove2() {
        final NullHandler h1 = new NullHandler();
        final Logger logger = Logger.getLogger("testHandlerRemove2");
        logger.removeHandler(h1);
        final Handler[] handlers = logger.getHandlers();
        assertEquals(0, handlers.length);
    }

    @Test
    public void testHandlerClear() {
        final NullHandler h1 = new NullHandler();
        final NullHandler h2 = new NullHandler();
        final NullHandler h3 = new NullHandler();
        final Logger logger = Logger.getLogger("testHandlerClear");
        logger.addHandler(h1);
        logger.addHandler(h2);
        logger.addHandler(h3);
        logger.clearHandlers();
        boolean f1 = false;
        boolean f2 = false;
        boolean f3 = false;
        for (Handler handler : logger.getHandlers()) {
            if (handler == h1)
                f1 = true;
            if (handler == h2)
                f2 = true;
            if (handler == h3)
                f3 = true;
        }
        assertFalse(f1, "Handler 1 wasn't removed");
        assertFalse(f2, "Handler 2 wasn't removed");
        assertFalse(f3, "Handler 3 wasn't removed");
    }

    @Test
    public void testHandlerRun() {
        final AtomicBoolean ran = new AtomicBoolean();
        final Handler handler = new CheckingHandler(ran);
        final Logger logger = Logger.getLogger("testHandlerRun");
        logger.setUseParentHandlers(false);
        logger.addHandler(handler);
        logger.setLevel(Level.INFO);
        handler.setLevel(Level.INFO);
        logger.info("This is a test.");
        assertTrue(ran.get(), "Handler wasn't run");
    }

    @Test
    public void testResourceBundle() {
        final ListHandler handler = new ListHandler();
        final Logger logger = Logger.getLogger("rbLogger", getClass().getName());
        logger.setLevel(Level.INFO);
        handler.setLevel(Level.INFO);
        logger.addHandler(handler);
        logger.log(Level.INFO, null, new IllegalArgumentException());
        logger.log(Level.INFO, "test", new IllegalArgumentException());
        assertNull(handler.messages.get(0));
        assertEquals("Test message", handler.messages.get(1));
    }

    @Test
    public void testJulResourceBundle() {
        final ListHandler handler = new ListHandler();
        final java.util.logging.Logger logger = java.util.logging.Logger.getLogger("rbLogger", getClass().getName());
        assertNotNull(logger.getResourceBundleName(), "Resource bundle name was expected");
        assertNotNull(logger.getResourceBundle(), "Resource bundle was expected");
        logger.setLevel(Level.INFO);
        handler.setLevel(Level.INFO);
        logger.addHandler(handler);
        logger.log(Level.INFO, null, new IllegalArgumentException());
        logger.log(Level.INFO, "test", new IllegalArgumentException());
        assertNull(handler.messages.get(0));
        assertEquals("Test message", handler.messages.get(1));
    }

    @Test
    public void testInheritedFilter() {
        final ListHandler handler = new ListHandler();
        final Logger parent = Logger.getLogger("parent", getClass().getName());
        parent.setLevel(Level.INFO);
        handler.setLevel(Level.INFO);
        parent.addHandler(handler);
        parent.setFilter(new RegexFilter(".*(?i)test.*"));

        final Logger child = Logger.getLogger("parent.child", getClass().getName());
        child.setUseParentFilters(true);
        child.setLevel(Level.INFO);

        child.info("This is a test message");
        child.info("This is another test message");
        child.info("One more message");

        assertEquals(2, handler.messages.size(), "Handler should have only contained two messages");

        // Clear the handler, reset the inherit filters
        handler.messages.clear();
        child.setUseParentFilters(false);

        child.info("This is a test message");
        child.info("This is another test message");
        child.info("One more message");

        assertEquals(3, handler.messages.size(), "Handler should have only contained three messages");

        parent.info("This is a test message");
        parent.info("This is another test message");
        parent.info("One more message");

        assertEquals(5, handler.messages.size(), "Handler should have only contained five messages");
    }

    private static final class ListHandler extends ExtHandler {
        final List<String> messages = Collections.synchronizedList(new ArrayList<>());

        ListHandler() {
            super();
            setFormatter(new DefaultFormatter());
        }

        @Override
        protected void doPublish(final ExtLogRecord record) {
            super.doPublish(record);
            messages.add(record.getFormattedMessage());
        }
    }

    private static final class CheckingHandler extends Handler {
        private final AtomicBoolean ran;

        public CheckingHandler(final AtomicBoolean ran) {
            this.ran = ran;
        }

        public void publish(final LogRecord record) {
            if (isLoggable(record)) {
                ran.set(true);
            }
        }

        public void flush() {
        }

        public void close() throws SecurityException {
        }
    }

    private static final class NullHandler extends Handler {

        public void publish(final LogRecord record) {
        }

        public void flush() {
        }

        public void close() throws SecurityException {
        }
    }
}
