package org.xbib.logging.configuration;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.ServiceLoader;
import java.util.Set;
import java.util.logging.Logger;
import org.xbib.logging.Level;
import org.xbib.logging.LogContext;
import org.xbib.logging.LogContextConfigurator;
import org.xbib.logging.formatters.DefaultFormatter;
import org.xbib.logging.handlers.ConsoleHandler;
import org.xbib.logging.util.StandardOutputStreams;

/**
 * A default log context configuration.
 * <p>
 * If the {@linkplain #configure(LogContext, InputStream) input stream} is {@code null} an attempt is made to find a
 * {@code logging.properties} file. If the file is not found, a {@linkplain ServiceLoader service loader} is
 * used to find the first implementation of a {@link LogContextConfigurator}. If that fails a default
 * {@link ConsoleHandler} is configured with the pattern {@code %d{yyyy-MM-dd'T'HH:mm:ssXXX} %-5p [%c] (%t) %s%e%n}.
 * </p>
 *
 * <p>
 * Locating the {@code logging.properties} happens in the following order:
 * <ul>
 * <li>The {@code logging.configuration} system property is checked</li>
 * <li>The current threads {@linkplain ClassLoader#getResourceAsStream(String)} class loader} for a
 * {@code logging.properties}</li>
 * <li>Finally {@link Class#getResourceAsStream(String)} is used to locate a {@code logging.properties}</li>
 * </ul>
 * </p>
 */
public class PropertyLogContextConfigurator implements LogContextConfigurator {

    public PropertyLogContextConfigurator() {
    }

    @Override
    public void configure(final LogContext logContext, final InputStream inputStream) {
        final InputStream configIn = inputStream != null ? inputStream : findConfiguration();
        final LogContext context = logContext == null ? LogContext.getLogContext() : logContext;
        // Configure the log context based on a property file
        if (configIn != null) {
            final Properties properties = new Properties();
            try (Reader reader = new InputStreamReader(configIn, StandardCharsets.UTF_8)) {
                properties.load(reader);
            } catch (IOException e) {
                throw new RuntimeException("Failed to configure log manager with configuration file", e);
            }
            final PropertyContextConfiguration configurator = PropertyContextConfiguration.configure(context, properties);
            context.attachIfAbsent(ContextConfiguration.CONTEXT_CONFIGURATION_KEY, configurator);
        } else {
            // Next check the service loader
            final Iterator<LogContextConfigurator> serviceLoader =
                    ServiceLoader.load(LogContextConfigurator.class, PropertyLogContextConfigurator.class.getClassLoader()).iterator();
            if (serviceLoader.hasNext()) {
                LogContextConfigurator logContextConfigurator = serviceLoader.next();
                logContextConfigurator.configure(context, null);
            } else {
                // Configure a default console handler, thread formatter and associated with the root logger
                final ConsoleHandler handler = new ConsoleHandler(new DefaultFormatter());
                handler.setLevel(Level.INFO);
                handler.setAutoFlush(true);
                final Logger rootLogger = context.getLogger("");
                rootLogger.setLevel(Level.INFO);
                rootLogger.addHandler(handler);
            }
        }
    }

    private static InputStream findConfiguration() {
        final String propLoc = System.getProperty("logging.configuration");
        if (propLoc != null) {
            try {
                return URI.create(propLoc).toURL().openStream();
            } catch (IOException e) {
                StandardOutputStreams.printError("Unable to read logging.configuration from '%s' (%s)%n", propLoc, e);
            }
        }
        try {
            return PropertyLogContextConfigurator.class.getClassLoader().getResourceAsStream("logging.properties");
        } catch (Exception e) {
            return null;
        }
    }
}
