package com.parse;

import android.content.Context;
import android.content.Intent;
import com.parse.ConnectivityNotifier;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.concurrent.Callable;
import java.util.concurrent.Executor;
import java.util.logging.Logger;
import org.json.JSONException;
import org.json.JSONObject;
import p137.C2739;
import p137.C2740;
import p137.C2742;
import p137.C2754;
import p137.InterfaceC2741;
import p138.p176.p177.p242.p246.p251.C4303;

/* JADX INFO: loaded from: classes.dex */
public class ParseCommandCache extends ParseEventuallyQueue {
    public static final Object lock = new Object();
    public File cachePath;
    public final ParseHttpClient httpClient;
    public Logger log;
    public ConnectivityNotifier notifier;
    public boolean running;
    public final Object runningLock;
    public boolean shouldStop;
    public boolean unprocessedCommandsExist;
    public ConnectivityNotifier.ConnectivityListener listener = new ConnectivityNotifier.ConnectivityListener() { // from class: com.parse.ParseCommandCache.1
        @Override // com.parse.ConnectivityNotifier.ConnectivityListener
        public void networkConnectivityStatusChanged(Context context, Intent intent) {
            final boolean booleanExtra = intent.getBooleanExtra("noConnectivity", false);
            final boolean zIsConnected = ConnectivityNotifier.isConnected(context);
            C2742.m4802(new Callable<Void>() { // from class: com.parse.ParseCommandCache.1.1
                @Override // java.util.concurrent.Callable
                public Void call() {
                    if (booleanExtra) {
                        ParseCommandCache.this.setConnected(false);
                        return null;
                    }
                    ParseCommandCache.this.setConnected(zIsConnected);
                    return null;
                }
            }, ParseExecutors.io());
        }
    };
    public int timeoutMaxRetries = 5;
    public double timeoutRetryWaitSeconds = 600.0d;
    public HashMap<File, C2754<JSONObject>> pendingTasks = new HashMap<>();

    public ParseCommandCache(Context context, ParseHttpClient parseHttpClient) {
        setConnected(false);
        this.shouldStop = false;
        this.running = false;
        this.runningLock = new Object();
        this.httpClient = parseHttpClient;
        this.log = Logger.getLogger("com.parse.ParseCommandCache");
        File file = new File(Parse.getParseDir(), "CommandCache");
        file.mkdirs();
        this.cachePath = file;
        if (Parse.getApplicationContext().checkCallingOrSelfPermission("android.permission.ACCESS_NETWORK_STATE") == 0) {
            setConnected(ConnectivityNotifier.isConnected(context));
            ConnectivityNotifier.singleton.tryToRegisterForNetworkStatusNotifications(context);
            ConnectivityNotifier connectivityNotifier = ConnectivityNotifier.singleton;
            this.notifier = connectivityNotifier;
            connectivityNotifier.addListener(this.listener);
            resume();
        }
    }

    public static int getPendingCount() {
        int length;
        synchronized (lock) {
            File file = new File(Parse.getParseDir(), "CommandCache");
            file.mkdirs();
            String[] list = file.list();
            length = list == null ? 0 : list.length;
        }
        return length;
    }

    public final void maybeRunAllCommandsNow(int i) {
        C2742 c2742M4805;
        synchronized (lock) {
            this.unprocessedCommandsExist = false;
            if (this.isConnected) {
                String[] list = this.cachePath.list();
                if (list != null && list.length != 0) {
                    Arrays.sort(list);
                    for (String str : list) {
                        File file = new File(this.cachePath, str);
                        try {
                            JSONObject fileToJSONObject = C4303.readFileToJSONObject(file);
                            final C2754<JSONObject> c2754 = this.pendingTasks.containsKey(file) ? this.pendingTasks.get(file) : null;
                            try {
                                final ParseRESTCommand parseRESTCommandCommandFromJSON = commandFromJSON(fileToJSONObject);
                                if (parseRESTCommandCommandFromJSON == null) {
                                    try {
                                        c2742M4805 = C2742.m4805((Object) null);
                                        if (c2754 != null) {
                                            c2754.m4827((JSONObject) null);
                                        }
                                    } catch (ParseException e) {
                                        if (e.code != 100) {
                                            removeFile(file);
                                        } else if (i > 0) {
                                            long jCurrentTimeMillis = System.currentTimeMillis();
                                            long j = ((long) (this.timeoutRetryWaitSeconds * 1000.0d)) + jCurrentTimeMillis;
                                            while (jCurrentTimeMillis < j) {
                                                if (!this.isConnected || this.shouldStop) {
                                                    return;
                                                }
                                                try {
                                                    lock.wait(j - jCurrentTimeMillis);
                                                } catch (InterruptedException unused) {
                                                    this.shouldStop = true;
                                                }
                                                jCurrentTimeMillis = System.currentTimeMillis();
                                                if (jCurrentTimeMillis < j - ((long) (this.timeoutRetryWaitSeconds * 1000.0d))) {
                                                    jCurrentTimeMillis = j - ((long) (this.timeoutRetryWaitSeconds * 1000.0d));
                                                }
                                            }
                                            maybeRunAllCommandsNow(i - 1);
                                        } else {
                                            setConnected(false);
                                        }
                                    }
                                } else {
                                    c2742M4805 = parseRESTCommandCommandFromJSON.executeAsync(this.httpClient).m4815(new InterfaceC2741<JSONObject, C2742<JSONObject>>(this) { // from class: com.parse.ParseCommandCache.4
                                        @Override // p137.InterfaceC2741
                                        public C2742<JSONObject> then(C2742<JSONObject> c2742) {
                                            String strOptString;
                                            C2754 c27542;
                                            String str2 = parseRESTCommandCommandFromJSON.localId;
                                            Exception excM4806 = c2742.m4806();
                                            if (excM4806 == null) {
                                                JSONObject jSONObjectM4812 = c2742.m4812();
                                                C2754 c27543 = c2754;
                                                if (c27543 != null) {
                                                    c27543.m4827(jSONObjectM4812);
                                                } else if (str2 != null && (strOptString = jSONObjectM4812.optString("objectId", null)) != null) {
                                                    ParseCorePlugins.INSTANCE.getLocalIdManager().setObjectId(str2, strOptString);
                                                }
                                            } else if ((!(excM4806 instanceof ParseException) || ((ParseException) excM4806).code != 100) && (c27542 = c2754) != null) {
                                                c27542.m4826(excM4806);
                                            }
                                            return c2742;
                                        }
                                    }, C2742.f8455, null);
                                }
                                waitForTaskWithoutLock(c2742M4805);
                                if (c2754 != null) {
                                    waitForTaskWithoutLock(c2754.f8503);
                                }
                                removeFile(file);
                            } catch (JSONException unused2) {
                                removeFile(file);
                            }
                        } catch (FileNotFoundException unused3) {
                        } catch (IOException unused4) {
                            removeFile(file);
                        } catch (JSONException unused5) {
                            removeFile(file);
                        }
                    }
                }
            }
        }
    }

    public final void removeFile(File file) {
        synchronized (lock) {
            this.pendingTasks.remove(file);
            try {
                commandFromJSON(C4303.readFileToJSONObject(file)).releaseLocalIds();
            } catch (Exception unused) {
            }
            C4303.deleteQuietly(file);
        }
    }

    public void resume() {
        synchronized (this.runningLock) {
            if (!this.running) {
                new Thread("ParseCommandCache.runLoop()") { // from class: com.parse.ParseCommandCache.2
                    @Override // java.lang.Thread, java.lang.Runnable
                    public void run() {
                        ParseCommandCache.this.runLoop();
                    }
                }.start();
                try {
                    this.runningLock.wait();
                } catch (InterruptedException unused) {
                    synchronized (lock) {
                        this.shouldStop = true;
                        lock.notifyAll();
                    }
                }
            }
        }
    }

    public final void runLoop() {
        boolean z;
        boolean z2;
        synchronized (this.runningLock) {
            if (this.running) {
                return;
            }
            this.running = true;
            this.runningLock.notifyAll();
            synchronized (lock) {
                z = (this.shouldStop || Thread.interrupted()) ? false : true;
            }
            while (z) {
                synchronized (lock) {
                    try {
                        try {
                            maybeRunAllCommandsNow(this.timeoutMaxRetries);
                            if (!this.shouldStop) {
                                try {
                                    if (!this.unprocessedCommandsExist) {
                                        lock.wait();
                                    }
                                } catch (InterruptedException unused) {
                                    this.shouldStop = true;
                                }
                            }
                        } finally {
                        }
                    } catch (Exception unused2) {
                    } catch (Throwable th) {
                        boolean z3 = this.shouldStop;
                        throw th;
                    }
                    z2 = !this.shouldStop;
                }
                z = z2;
            }
            synchronized (this.runningLock) {
                this.running = false;
                this.runningLock.notifyAll();
            }
        }
    }

    public void setConnected(boolean z) {
        synchronized (lock) {
            if (this.isConnected != z && z) {
                lock.notifyAll();
            }
            this.isConnected = z;
        }
    }

    public final <T> T waitForTaskWithoutLock(C2742<T> c2742) {
        T t;
        synchronized (lock) {
            final C2740 c2740 = new C2740(false);
            c2742.m4809((InterfaceC2741<T, TContinuationResult>) new InterfaceC2741<T, Void>(this) { // from class: com.parse.ParseCommandCache.3
                @Override // p137.InterfaceC2741
                public /* bridge */ /* synthetic */ Void then(C2742 c27422) {
                    then();
                    return null;
                }

                public Void then() {
                    c2740.f8453 = (T) true;
                    synchronized (ParseCommandCache.lock) {
                        ParseCommandCache.lock.notifyAll();
                    }
                    return null;
                }
            }, (Executor) C2742.f8454, (C2739) null);
            while (!((Boolean) c2740.f8453).booleanValue()) {
                try {
                    lock.wait();
                } catch (InterruptedException unused) {
                    this.shouldStop = true;
                }
            }
            t = (T) C4303.wait(c2742);
        }
        return t;
    }
}
