/*
 * Decompiled with CFR 0.152.
 */
package org.apache.logging.log4j.util;

import java.io.IOException;
import java.net.URL;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Properties;
import java.util.concurrent.CopyOnWriteArraySet;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.spi.Provider;
import org.apache.logging.log4j.status.StatusLogger;
import org.apache.logging.log4j.util.LoaderUtil;
import org.apache.logging.log4j.util.PropertiesUtil;

public final class ProviderUtil {
    protected static final String PROVIDER_RESOURCE = "META-INF/log4j-provider.properties";
    private static final String API_VERSION = "Log4jAPIVersion";
    private static final String[] COMPATIBLE_API_VERSIONS = new String[]{"2.0.0"};
    private static final Logger LOGGER = StatusLogger.getLogger();
    private static final Collection<Provider> PROVIDERS = new CopyOnWriteArraySet<Provider>();

    private ProviderUtil() {
    }

    protected static void loadProviders(Enumeration<URL> enumResources, ClassLoader cl) {
        if (enumResources != null) {
            while (enumResources.hasMoreElements()) {
                URL url = enumResources.nextElement();
                ProviderUtil.loadProvider(url, cl);
            }
        }
    }

    protected static void loadProvider(URL url, ClassLoader cl) {
        try {
            Properties props = PropertiesUtil.loadClose(url.openStream(), url);
            if (ProviderUtil.validVersion(props.getProperty(API_VERSION))) {
                PROVIDERS.add(new Provider(props, url, cl));
            }
        }
        catch (IOException e) {
            LOGGER.error("Unable to open {}", url, e);
        }
    }

    public static Iterable<Provider> getProviders() {
        return PROVIDERS;
    }

    public static boolean hasProviders() {
        return !PROVIDERS.isEmpty();
    }

    public static ClassLoader findClassLoader() {
        return LoaderUtil.getThreadContextClassLoader();
    }

    private static boolean validVersion(String version) {
        for (String v : COMPATIBLE_API_VERSIONS) {
            if (!version.startsWith(v)) continue;
            return true;
        }
        return false;
    }

    static {
        ClassLoader cl = ProviderUtil.findClassLoader();
        Enumeration<URL> enumResources = null;
        try {
            enumResources = cl.getResources(PROVIDER_RESOURCE);
        }
        catch (IOException e) {
            LOGGER.fatal("Unable to locate {}", PROVIDER_RESOURCE, e);
        }
        ProviderUtil.loadProviders(enumResources, cl);
    }
}
