package com.apkstudio.appd77d4cbcc9e24c16a7eed07b0ac8781f;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Looper;
import java.io.OutputStream;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.net.ssl.HttpsURLConnection;
import org.json.JSONObject;

/* JADX INFO: loaded from: classes2.dex */
final class OpenStats {
    private static final String ENDPOINT = "https://xiswfm.com/events/open/3b4e43b4-ab83-48d4-b7f0-0aa31e6ad921";
    private static final long INITIAL_RETRY_MS = 5000;
    private static final String INSTALL_ID = "installId";
    private static final long MAX_RETRY_MS = 300000;
    private static boolean configurationChange;
    private static OpenStats instance;
    private static int visibleActivities;
    private final String installId;
    private final SharedPreferences queue;
    private boolean sending;
    private final Handler main = new Handler(Looper.getMainLooper());
    private final ExecutorService sender = Executors.newSingleThreadExecutor();
    private final Runnable retry = new Runnable() { // from class: com.apkstudio.appd77d4cbcc9e24c16a7eed07b0ac8781f.OpenStats$$ExternalSyntheticLambda0
        @Override // java.lang.Runnable
        public final void run() {
            this.f$0.flush();
        }
    };
    private long retryDelay = INITIAL_RETRY_MS;

    private OpenStats(Context context) {
        this.queue = context.getSharedPreferences("apkstudio_opens", 0);
        String string = this.queue.getString(INSTALL_ID, null);
        this.installId = string == null ? UUID.randomUUID().toString() : string;
        if (string == null) {
            this.queue.edit().putString(INSTALL_ID, this.installId).apply();
        }
    }

    static void started(Context context, boolean z) {
        int i = visibleActivities + 1;
        visibleActivities = i;
        if (i != 1) {
            return;
        }
        if (instance == null) {
            instance = new OpenStats(context.getApplicationContext());
        }
        if (!configurationChange && !z) {
            instance.queue.edit().putLong(UUID.randomUUID().toString(), System.currentTimeMillis()).apply();
        }
        configurationChange = false;
        instance.retryDelay = INITIAL_RETRY_MS;
        instance.flush();
    }

    static void stopped(boolean z) {
        int i = visibleActivities - 1;
        visibleActivities = i;
        if (i == 0) {
            configurationChange = z;
            instance.main.removeCallbacks(instance.retry);
        }
    }

    /* JADX INFO: Access modifiers changed from: private */
    public void flush() {
        if (this.sending || visibleActivities == 0 || this.queue.getAll().size() <= 1) {
            return;
        }
        this.sending = true;
        this.sender.execute(new Runnable() { // from class: com.apkstudio.appd77d4cbcc9e24c16a7eed07b0ac8781f.OpenStats$$ExternalSyntheticLambda1
            @Override // java.lang.Runnable
            public final void run() {
                this.f$0.m15xf292d3e2();
            }
        });
    }

    /* JADX INFO: renamed from: lambda$flush$1$com-apkstudio-appd77d4cbcc9e24c16a7eed07b0ac8781f-OpenStats, reason: not valid java name */
    /* synthetic */ void m15xf292d3e2() {
        final boolean zSendQueued = sendQueued();
        this.main.post(new Runnable() { // from class: com.apkstudio.appd77d4cbcc9e24c16a7eed07b0ac8781f.OpenStats$$ExternalSyntheticLambda2
            @Override // java.lang.Runnable
            public final void run() {
                this.f$0.m14x381d3361(zSendQueued);
            }
        });
    }

    /* JADX INFO: renamed from: lambda$flush$0$com-apkstudio-appd77d4cbcc9e24c16a7eed07b0ac8781f-OpenStats, reason: not valid java name */
    /* synthetic */ void m14x381d3361(boolean z) {
        this.sending = false;
        if (visibleActivities == 0) {
            return;
        }
        if (z) {
            this.retryDelay = INITIAL_RETRY_MS;
            flush();
        } else {
            this.main.postDelayed(this.retry, this.retryDelay);
            this.retryDelay = Math.min(this.retryDelay * 2, MAX_RETRY_MS);
        }
    }

    private boolean sendQueued() {
        for (Map.Entry<String, ?> entry : this.queue.getAll().entrySet()) {
            if (entry.getValue() instanceof Long) {
                if (!send(entry.getKey(), ((Long) entry.getValue()).longValue())) {
                    return false;
                }
                this.queue.edit().remove(entry.getKey()).apply();
            }
        }
        return true;
    }

    private boolean send(String str, long j) throws Throwable {
        HttpsURLConnection httpsURLConnection = null;
        try {
            byte[] bytes = new JSONObject().put(INSTALL_ID, this.installId).put("eventId", str).put("openedAt", j).toString().getBytes(StandardCharsets.UTF_8);
            HttpsURLConnection httpsURLConnection2 = (HttpsURLConnection) new URL(ENDPOINT).openConnection();
            try {
                httpsURLConnection2.setConnectTimeout(6000);
                httpsURLConnection2.setReadTimeout(6000);
                httpsURLConnection2.setInstanceFollowRedirects(false);
                httpsURLConnection2.setRequestMethod("POST");
                httpsURLConnection2.setRequestProperty("Content-Type", "application/json");
                httpsURLConnection2.setRequestProperty("User-Agent", "APKStudio-Open/1");
                httpsURLConnection2.setDoOutput(true);
                httpsURLConnection2.setFixedLengthStreamingMode(bytes.length);
                OutputStream outputStream = httpsURLConnection2.getOutputStream();
                try {
                    outputStream.write(bytes);
                    if (outputStream != null) {
                        outputStream.close();
                    }
                    int responseCode = httpsURLConnection2.getResponseCode();
                    boolean z = (responseCode >= 200 && responseCode < 300) || responseCode == 400 || responseCode == 410 || responseCode == 422;
                    if (httpsURLConnection2 != null) {
                        httpsURLConnection2.disconnect();
                    }
                    return z;
                } catch (Throwable th) {
                    if (outputStream != null) {
                        try {
                            outputStream.close();
                        } catch (Throwable th2) {
                            th.addSuppressed(th2);
                        }
                    }
                    throw th;
                }
            } catch (Exception e) {
                httpsURLConnection = httpsURLConnection2;
                if (httpsURLConnection != null) {
                    httpsURLConnection.disconnect();
                }
                return false;
            } catch (Throwable th3) {
                th = th3;
                httpsURLConnection = httpsURLConnection2;
                if (httpsURLConnection != null) {
                    httpsURLConnection.disconnect();
                }
                throw th;
            }
        } catch (Exception e2) {
        } catch (Throwable th4) {
            th = th4;
        }
    }
}
