package org.xbib.logging;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.ServiceConfigurationError;
import java.util.ServiceLoader;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiFunction;
import java.util.function.Function;
import org.xbib.logging.configuration.PropertyLogContextConfigurator;
import org.xbib.logging.util.StandardOutputStreams;

/**
 * Simplified log manager. Designed to work around the (many) design flaws of the JDK platform log manager.
 */
public final class LogManager extends java.util.logging.LogManager {

    static {
        try {
            // Ensure the StandardOutputStreams are initialized early to capture the current System.out and System.err.
            ClassLoader.getSystemClassLoader().loadClass(StandardOutputStreams.class.getName());
        } catch (ClassNotFoundException ignore) {
            // ignore
        }
    }

    private static final AtomicBoolean CONFIGURED = new AtomicBoolean();

    // Configuration
    private final AtomicReference<LogContextConfigurator> configuratorRef = new AtomicReference<>();

    /**
     * Construct a new logmanager instance. Attempts to plug a known memory leak in {@link java.util.logging.Level} as
     * well.
     */
    public LogManager() {
    }

    /**
     * Configure the system log context initially.
     */
    @Override
    public void readConfiguration() {
        if (CONFIGURED.compareAndSet(false, true)) {
            doConfigure(null);
        }
    }

    /**
     * Configure the system log context initially with a given input stream.
     *
     * @param inputStream the input stream
     */
    @Override
    public void readConfiguration(InputStream inputStream) {
        if (CONFIGURED.compareAndSet(false, true)) {
            doConfigure(inputStream);
        }
    }

    /**
     * Does nothing.
     *
     * @param mapper not used
     */
    @Override
    public void updateConfiguration(final Function<String, BiFunction<String, String, String>> mapper) throws IOException {
        // no operation - the configuration API should be used
    }

    /**
     * Does nothing.
     *
     * @param ins    not used
     * @param mapper not used
     */
    @Override
    public void updateConfiguration(final InputStream ins, final Function<String, BiFunction<String, String, String>> mapper)
            throws IOException {
        // no operation - the configuration API should be used
    }

    /**
     * Configuration listeners are not currently supported.
     *
     * @param listener not used
     * @return this log manager
     */
    @Override
    public java.util.logging.LogManager addConfigurationListener(final Runnable listener) {
        // no operation
        return this;
    }

    /**
     * Configuration listeners are not currently supported.
     *
     * @param listener not used
     */
    @Override
    public void removeConfigurationListener(final Runnable listener) {
        // no operation
    }

    /**
     * Does nothing. Properties are not supported.
     *
     * @param name ignored
     * @return {@code null}
     */
    @Override
    public String getProperty(String name) {
        // no properties
        return null;
    }

    /**
     * Does nothing. This method only causes trouble.
     */
    @Override
    public void reset() {
        // no operation!
    }

    @Override
    public Enumeration<String> getLoggerNames() {
        return LogContext.getLogContext().getLoggerNames();
    }

    /**
     * Do nothing. Loggers are only added/acquired via {@link #getLogger(String)}.
     *
     * @param logger ignored
     * @return {@code false}
     */
    @Override
    public boolean addLogger(java.util.logging.Logger logger) {
        return false;
    }

    /**
     * Get or create a logger with the given name.
     *
     * @param name the logger name
     * @return the corresponding logger
     */
    @Override
    public Logger getLogger(String name) {
        return LogContext.getLogContext().getLogger(name);
    }

    private void doConfigure(InputStream inputStream) {
        final AtomicReference<LogContextConfigurator> configuratorRef = this.configuratorRef;
        LogContextConfigurator configurator = configuratorRef.get();
        if (configurator == null) {
            synchronized (configuratorRef) {
                configurator = configuratorRef.get();
                if (configurator == null) {
                    int best = Integer.MAX_VALUE;
                    LogContextConfiguratorFactory factory = null;
                    final ServiceLoader<LogContextConfiguratorFactory> serviceLoader =
                            ServiceLoader.load(LogContextConfiguratorFactory.class, LogManager.class.getClassLoader());
                    final Iterator<LogContextConfiguratorFactory> iterator = serviceLoader.iterator();
                    List<Throwable> problems = null;
                    for (; ; )
                        try {
                            if (!iterator.hasNext())
                                break;
                            final LogContextConfiguratorFactory f = iterator.next();
                            if (f.priority() < best || factory == null) {
                                best = f.priority();
                                factory = f;
                            }
                        } catch (Throwable t) {
                            if (problems == null)
                                problems = new ArrayList<>(4);
                            problems.add(t);
                        }
                    configurator = factory == null ? null : factory.create();
                    if (configurator == null) {
                        if (problems == null) {
                            configuratorRef.set(configurator = new PropertyLogContextConfigurator());
                        } else {
                            final ServiceConfigurationError e = new ServiceConfigurationError(
                                    "Failed to configure log configurator service");
                            for (Throwable problem : problems) {
                                e.addSuppressed(problem);
                            }
                            throw e;
                        }
                    }
                }
            }
        }
        configurator.configure(LogContext.getSystemLogContext(), inputStream);
    }
}
