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

package io.sentry;

import org.jetbrains.annotations.VisibleForTesting;
import java.io.IOException;
import io.sentry.util.IntegrationUtils;
import org.jetbrains.annotations.TestOnly;
import io.sentry.util.Objects;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.NotNull;
import java.io.Closeable;

public final class ShutdownHookIntegration implements Integration, Closeable
{
    @NotNull
    private final Runtime runtime;
    @Nullable
    private Thread thread;
    
    @TestOnly
    public ShutdownHookIntegration(@NotNull final Runtime runtime) {
        this.runtime = Objects.requireNonNull(runtime, "Runtime is required");
    }
    
    public ShutdownHookIntegration() {
        this(Runtime.getRuntime());
    }
    
    @Override
    public void register(@NotNull final IScopes scopes, @NotNull final SentryOptions options) {
        Objects.requireNonNull(scopes, "Scopes are required");
        Objects.requireNonNull(options, "SentryOptions is required");
        if (options.isEnableShutdownHook()) {
            this.thread = new Thread(() -> scopes.flush(options.getFlushTimeoutMillis()), "sentry-shutdownhook");
            this.handleShutdownInProgress(() -> {
                this.runtime.addShutdownHook(this.thread);
                options.getLogger().log(SentryLevel.DEBUG, "ShutdownHookIntegration installed.", new Object[0]);
                IntegrationUtils.addIntegrationToSdkVersion("ShutdownHook");
            });
        }
        else {
            options.getLogger().log(SentryLevel.INFO, "enableShutdownHook is disabled.", new Object[0]);
        }
    }
    
    @Override
    public void close() throws IOException {
        if (this.thread != null) {
            this.handleShutdownInProgress(() -> this.runtime.removeShutdownHook(this.thread));
        }
    }
    
    private void handleShutdownInProgress(@NotNull final Runnable runnable) {
        try {
            runnable.run();
        }
        catch (final IllegalStateException e) {
            final String message = e.getMessage();
            if (message != null) {
                if (message.equals("Shutdown in progress")) {
                    return;
                }
                if (message.equals("VM already shutting down")) {
                    return;
                }
            }
            throw e;
        }
    }
    
    @VisibleForTesting
    @Nullable
    Thread getHook() {
        return this.thread;
    }
}
