package org.xbib.logging.ext;

import java.util.Collections;
import java.util.Set;
import java.util.concurrent.ConcurrentMap;
import java.util.function.Function;
import org.xbib.logging.LogContext;
import org.xbib.logging.LogContextSelector;
import org.xbib.logging.util.CopyOnWriteMap;
import org.xbib.logging.util.StackWalkerUtil;

/**
 * A log context selector which chooses a log context based on the caller's classloader.
 */
public final class ClassLoaderLogContextSelector implements LogContextSelector {

    /**
     * Construct a new instance. If no matching log context is found, the provided default selector is consulted.
     *
     * @param defaultSelector the selector to consult if no matching log context is found
     */
    public ClassLoaderLogContextSelector(final LogContextSelector defaultSelector) {
        this(defaultSelector, false);
    }

    /**
     * Construct a new instance. If no matching log context is found, the provided default selector is consulted.
     * <p/>
     * If the {@code checkParentClassLoaders} is set to {@code true} this selector recursively searches the class loader
     * parents until a match is found or a {@code null} parent is found.
     *
     * @param defaultSelector         the selector to consult if no matching log context is found
     * @param checkParentClassLoaders {@code true} if the {@link LogContext log context} could not
     *                                found for the class loader and the {@link ClassLoader#getParent() parent class
     *                                loader} should be checked
     */
    public ClassLoaderLogContextSelector(final LogContextSelector defaultSelector, final boolean checkParentClassLoaders) {
        this.defaultSelector = defaultSelector;
        this.checkParentClassLoaders = checkParentClassLoaders;
    }

    /**
     * Construct a new instance. If no matching log context is found, the system context is used.
     */
    public ClassLoaderLogContextSelector() {
        this(false);
    }

    /**
     * Construct a new instance. If no matching log context is found, the system context is used.
     * <p/>
     * If the {@code checkParentClassLoaders} is set to {@code true} this selector recursively searches the class loader
     * parents until a match is found or a {@code null} parent is found.
     *
     * @param checkParentClassLoaders {@code true} if the {@link LogContext log context} could not
     *                                found for the class loader and the {@link ClassLoader#getParent() parent class
     *                                loader} should be checked
     */
    public ClassLoaderLogContextSelector(final boolean checkParentClassLoaders) {
        this(LogContext.DEFAULT_LOG_CONTEXT_SELECTOR, checkParentClassLoaders);
    }

    private final LogContextSelector defaultSelector;

    private final ConcurrentMap<ClassLoader, LogContext> contextMap = new CopyOnWriteMap<>();
    private final Set<ClassLoader> logApiClassLoaders = Collections.newSetFromMap(new CopyOnWriteMap<>());
    private final boolean checkParentClassLoaders;

    private final Function<ClassLoader, LogContext> logContextFinder = new Function<>() {
        @Override
        public LogContext apply(final ClassLoader classLoader) {

            final LogContext context = contextMap.get(classLoader);
            if (context != null) {
                return context;
            }
            final ClassLoader parent = classLoader.getParent();
            if (parent != null && checkParentClassLoaders && !logApiClassLoaders.contains(parent)) {
                return apply(parent);
            }
            return null;
        }
    };

    /**
     * {@inheritDoc} This instance will consult the call stack to see if any calling classloader is associated
     * with any log context.
     */
    @Override
    public LogContext getLogContext() {
        final LogContext result = StackWalkerUtil.logContextFinder(logApiClassLoaders, logContextFinder);
        if (result != null) {
            return result;
        }
        return defaultSelector.getLogContext();
    }

    /**
     * Register a class loader which is a known log API, and thus should be skipped over when searching for the
     * log context to use for the caller class.
     *
     * @param apiClassLoader the API class loader
     * @return {@code true} if this class loader was previously unknown, or {@code false} if it was already registered
     */
    public boolean addLogApiClassLoader(ClassLoader apiClassLoader) {
        return logApiClassLoaders.add(apiClassLoader);
    }

    /**
     * Remove a class loader from the known log APIs set.
     *
     * @param apiClassLoader the API class loader
     * @return {@code true} if the class loader was removed, or {@code false} if it was not known to this selector
     */
    public boolean removeLogApiClassLoader(ClassLoader apiClassLoader) {
        return logApiClassLoaders.remove(apiClassLoader);
    }

    /**
     * Register a class loader with a log context. This method requires the {@code registerLogContext}
     * {@link RuntimePermission}.
     *
     * @param classLoader the classloader
     * @param logContext  the log context
     * @throws IllegalArgumentException if the classloader is already associated with a log context
     */
    public void registerLogContext(ClassLoader classLoader, LogContext logContext) throws IllegalArgumentException {
        if (contextMap.putIfAbsent(classLoader, logContext) != null) {
            throw new IllegalArgumentException(
                    "ClassLoader instance is already registered to a log context (" + classLoader + ")");
        }
    }

    /**
     * Unregister a class loader/log context association. This method requires the {@code unregisterLogContext}
     * {@link RuntimePermission}.
     *
     * @param classLoader the classloader
     * @param logContext  the log context
     * @return {@code true} if the association exists and was removed, {@code false} otherwise
     */
    public boolean unregisterLogContext(ClassLoader classLoader, LogContext logContext) {
        return contextMap.remove(classLoader, logContext);
    }
}
