package org.xbib.logging.log4j;

import java.net.URI;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;

import org.apache.logging.log4j.spi.LoggerContext;
import org.apache.logging.log4j.spi.LoggerContextFactory;
import org.apache.logging.log4j.status.StatusLogger;
import org.xbib.logging.LogContext;
import org.xbib.logging.Logger;

/**
 * A context factory backed by LogManager.
 */
public class XbibLoggerContextFactory implements LoggerContextFactory {

    private static final Logger.AttachmentKey<Map<Object, LoggerContext>> CONTEXT_KEY = new Logger.AttachmentKey<>();

    private static final String ROOT_LOGGER_NAME = "";

    private final ReentrantLock lock = new ReentrantLock();

    public XbibLoggerContextFactory() {
    }

    @Override
    public LoggerContext getContext(final String fqcn, final ClassLoader loader, final Object externalContext,
            final boolean currentContext) {
        return getLoggerContext(loader, externalContext, currentContext);
    }

    @Override
    public LoggerContext getContext(final String fqcn, final ClassLoader loader, final Object externalContext,
            final boolean currentContext, final URI configLocation, final String name) {
        try {
            return getLoggerContext(loader, externalContext, currentContext);
        } finally {
            // Done in a finally block as the StatusLogger may not be configured until the call to getLoggerContext()
            if (configLocation != null) {
                StatusLogger.getLogger().warn(
                        "Configuration is not allowed for the LogManager binding. Ignoring configuration file {}",
                        configLocation);
            }
        }
    }

    @Override
    public void removeContext(final LoggerContext context) {
        // Check the context type and if it's not a XbibLoggerContext there is nothing for us to do.
        if (context instanceof XbibLoggerContext) {
            final LogContext logContext = ((XbibLoggerContext) context).getLogContext();
            lock.lock();
            try {
                final Map<Object, LoggerContext> contexts = logContext.getAttachment(ROOT_LOGGER_NAME, CONTEXT_KEY);
                if (contexts != null) {
                    final Iterator<LoggerContext> iter = contexts.values().iterator();
                    while (iter.hasNext()) {
                        final LoggerContext c = iter.next();
                        if (c.equals(context)) {
                            iter.remove();
                            break;
                        }
                    }
                    if (contexts.isEmpty()) {
                        final Logger rootLogger = logContext.getLogger(ROOT_LOGGER_NAME);
                        detach(rootLogger);
                        XbibStatusListener.remove(logContext);
                    }
                }
            } finally {
                lock.unlock();
            }
        }
    }

    private LoggerContext getLoggerContext(final ClassLoader classLoader, final Object externalContext,
            final boolean currentContext) {
        if (currentContext || classLoader == null) {
            return getOrCreateLoggerContext(LogContext.getLogContext(), externalContext);
        }
        final ClassLoader current = getTccl();
        try {
            setTccl(classLoader);
            return getOrCreateLoggerContext(LogContext.getLogContext(), externalContext);
        } finally {
            setTccl(current);
        }
    }

    private LoggerContext getOrCreateLoggerContext(final LogContext logContext, final Object externalContext) {
        final Logger rootLogger = logContext.getLogger(ROOT_LOGGER_NAME);
        lock.lock();
        try {
            Map<Object, LoggerContext> contexts = rootLogger.getAttachment(CONTEXT_KEY);
            if (contexts == null) {
                contexts = new HashMap<>();
                attach(rootLogger, contexts);
            }
            XbibStatusListener.registerIfAbsent(logContext);
            return contexts.computeIfAbsent(externalContext, o -> new XbibLoggerContext(logContext, externalContext));
        } finally {
            lock.unlock();
        }
    }

    private static void attach(final Logger logger, final Map<Object, LoggerContext> value) {
        logger.attach(CONTEXT_KEY, value);
    }

    private static void detach(final Logger logger) {
        logger.detach(CONTEXT_KEY);
    }

    private static ClassLoader getTccl() {
        return Thread.currentThread().getContextClassLoader();
    }

    private static void setTccl(final ClassLoader classLoader) {
        Thread.currentThread().setContextClassLoader(classLoader);
    }
}
