// 
// Decompiled by Procyon v0.6.0
// 

package io.sentry.internal.modules;

import java.io.IOException;
import io.sentry.SentryLevel;
import java.io.Reader;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.TreeMap;
import java.io.InputStream;
import io.sentry.ISentryLifecycleToken;
import org.jetbrains.annotations.Nullable;
import java.util.Map;
import io.sentry.util.AutoClosableReentrantLock;
import org.jetbrains.annotations.NotNull;
import io.sentry.ILogger;
import java.nio.charset.Charset;
import org.jetbrains.annotations.ApiStatus;

@ApiStatus.Internal
public abstract class ModulesLoader implements IModulesLoader
{
    private static final Charset UTF_8;
    public static final String EXTERNAL_MODULES_FILENAME = "sentry-external-modules.txt";
    @NotNull
    protected final ILogger logger;
    @NotNull
    private final AutoClosableReentrantLock modulesLock;
    @Nullable
    private volatile Map<String, String> cachedModules;
    
    public ModulesLoader(@NotNull final ILogger logger) {
        this.modulesLock = new AutoClosableReentrantLock();
        this.cachedModules = null;
        this.logger = logger;
    }
    
    @Nullable
    @Override
    public Map<String, String> getOrLoadModules() {
        if (this.cachedModules == null) {
            try (final ISentryLifecycleToken ignored = this.modulesLock.acquire()) {
                if (this.cachedModules == null) {
                    this.cachedModules = this.loadModules();
                }
            }
        }
        return this.cachedModules;
    }
    
    protected abstract Map<String, String> loadModules();
    
    protected Map<String, String> parseStream(@NotNull final InputStream stream) {
        final Map<String, String> modules = new TreeMap<String, String>();
        try (final BufferedReader reader = new BufferedReader(new InputStreamReader(stream, ModulesLoader.UTF_8))) {
            for (String module = reader.readLine(); module != null; module = reader.readLine()) {
                final int sep = module.lastIndexOf(58);
                final String group = module.substring(0, sep);
                final String version = module.substring(sep + 1);
                modules.put(group, version);
            }
            this.logger.log(SentryLevel.DEBUG, "Extracted %d modules from resources.", modules.size());
        }
        catch (final IOException e) {
            this.logger.log(SentryLevel.ERROR, "Error extracting modules.", e);
        }
        catch (final RuntimeException e2) {
            this.logger.log(SentryLevel.ERROR, e2, "%s file is malformed.", "sentry-external-modules.txt");
        }
        return modules;
    }
    
    static {
        UTF_8 = Charset.forName("UTF-8");
    }
}
