package com.google.firebase.firestore.remote;

import C0.D;
import com.google.android.gms.tasks.Task;
import com.google.android.gms.tasks.TaskCompletionSource;
import com.google.firebase.firestore.AggregateField;
import com.google.firebase.firestore.FirebaseFirestoreException;
import com.google.firebase.firestore.core.Query;
import com.google.firebase.firestore.model.DocumentKey;
import com.google.firebase.firestore.model.MutableDocument;
import com.google.firebase.firestore.model.SnapshotVersion;
import com.google.firebase.firestore.model.mutation.Mutation;
import com.google.firebase.firestore.model.mutation.MutationResult;
import com.google.firebase.firestore.remote.FirestoreChannel;
import com.google.firebase.firestore.remote.WatchStream;
import com.google.firebase.firestore.remote.WriteStream;
import com.google.firebase.firestore.util.Assert;
import com.google.firebase.firestore.util.AsyncQueue;
import com.google.firebase.firestore.util.Util;
import com.google.protobuf.C1343z;
import e4.C;
import e4.C1979f;
import e4.C1981g;
import e4.C1983h;
import e4.C1989k;
import e4.C1991l;
import e4.C1993m;
import e4.H0;
import e4.M;
import e4.N;
import e4.O;
import e4.Y;
import e4.z0;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.net.ssl.SSLHandshakeException;
import k4.h0;
import k4.i0;
import k4.q0;
import k4.r0;
import r4.AbstractC2890c;
import r4.C2889b;

/* JADX INFO: loaded from: classes3.dex */
public class Datastore {
    static final String SSL_DEPENDENCY_ERROR_MESSAGE = "The Cloud Firestore client failed to establish a secure connection. This is likely a problem with your app, rather than with Cloud Firestore itself. See https://bit.ly/2XFpdma for instructions on how to enable TLS on Android 4.x devices.";
    static final Set<String> WHITE_LISTED_HEADERS = new HashSet(Arrays.asList("date", "x-google-backends", "x-google-netmon-label", "x-google-service", "x-google-gfe-request-trace"));
    private final FirestoreChannel channel;
    protected final RemoteSerializer serializer;
    private final AsyncQueue workerQueue;

    /* JADX INFO: renamed from: com.google.firebase.firestore.remote.Datastore$2, reason: invalid class name */
    public static /* synthetic */ class AnonymousClass2 {
        static final /* synthetic */ int[] $SwitchMap$com$google$firebase$firestore$FirebaseFirestoreException$Code;

        static {
            int[] iArr = new int[FirebaseFirestoreException.Code.values().length];
            $SwitchMap$com$google$firebase$firestore$FirebaseFirestoreException$Code = iArr;
            try {
                iArr[FirebaseFirestoreException.Code.OK.ordinal()] = 1;
            } catch (NoSuchFieldError unused) {
            }
            try {
                $SwitchMap$com$google$firebase$firestore$FirebaseFirestoreException$Code[FirebaseFirestoreException.Code.CANCELLED.ordinal()] = 2;
            } catch (NoSuchFieldError unused2) {
            }
            try {
                $SwitchMap$com$google$firebase$firestore$FirebaseFirestoreException$Code[FirebaseFirestoreException.Code.UNKNOWN.ordinal()] = 3;
            } catch (NoSuchFieldError unused3) {
            }
            try {
                $SwitchMap$com$google$firebase$firestore$FirebaseFirestoreException$Code[FirebaseFirestoreException.Code.DEADLINE_EXCEEDED.ordinal()] = 4;
            } catch (NoSuchFieldError unused4) {
            }
            try {
                $SwitchMap$com$google$firebase$firestore$FirebaseFirestoreException$Code[FirebaseFirestoreException.Code.RESOURCE_EXHAUSTED.ordinal()] = 5;
            } catch (NoSuchFieldError unused5) {
            }
            try {
                $SwitchMap$com$google$firebase$firestore$FirebaseFirestoreException$Code[FirebaseFirestoreException.Code.INTERNAL.ordinal()] = 6;
            } catch (NoSuchFieldError unused6) {
            }
            try {
                $SwitchMap$com$google$firebase$firestore$FirebaseFirestoreException$Code[FirebaseFirestoreException.Code.UNAVAILABLE.ordinal()] = 7;
            } catch (NoSuchFieldError unused7) {
            }
            try {
                $SwitchMap$com$google$firebase$firestore$FirebaseFirestoreException$Code[FirebaseFirestoreException.Code.UNAUTHENTICATED.ordinal()] = 8;
            } catch (NoSuchFieldError unused8) {
            }
            try {
                $SwitchMap$com$google$firebase$firestore$FirebaseFirestoreException$Code[FirebaseFirestoreException.Code.INVALID_ARGUMENT.ordinal()] = 9;
            } catch (NoSuchFieldError unused9) {
            }
            try {
                $SwitchMap$com$google$firebase$firestore$FirebaseFirestoreException$Code[FirebaseFirestoreException.Code.NOT_FOUND.ordinal()] = 10;
            } catch (NoSuchFieldError unused10) {
            }
            try {
                $SwitchMap$com$google$firebase$firestore$FirebaseFirestoreException$Code[FirebaseFirestoreException.Code.ALREADY_EXISTS.ordinal()] = 11;
            } catch (NoSuchFieldError unused11) {
            }
            try {
                $SwitchMap$com$google$firebase$firestore$FirebaseFirestoreException$Code[FirebaseFirestoreException.Code.PERMISSION_DENIED.ordinal()] = 12;
            } catch (NoSuchFieldError unused12) {
            }
            try {
                $SwitchMap$com$google$firebase$firestore$FirebaseFirestoreException$Code[FirebaseFirestoreException.Code.FAILED_PRECONDITION.ordinal()] = 13;
            } catch (NoSuchFieldError unused13) {
            }
            try {
                $SwitchMap$com$google$firebase$firestore$FirebaseFirestoreException$Code[FirebaseFirestoreException.Code.ABORTED.ordinal()] = 14;
            } catch (NoSuchFieldError unused14) {
            }
            try {
                $SwitchMap$com$google$firebase$firestore$FirebaseFirestoreException$Code[FirebaseFirestoreException.Code.OUT_OF_RANGE.ordinal()] = 15;
            } catch (NoSuchFieldError unused15) {
            }
            try {
                $SwitchMap$com$google$firebase$firestore$FirebaseFirestoreException$Code[FirebaseFirestoreException.Code.UNIMPLEMENTED.ordinal()] = 16;
            } catch (NoSuchFieldError unused16) {
            }
            try {
                $SwitchMap$com$google$firebase$firestore$FirebaseFirestoreException$Code[FirebaseFirestoreException.Code.DATA_LOSS.ordinal()] = 17;
            } catch (NoSuchFieldError unused17) {
            }
        }
    }

    public Datastore(AsyncQueue asyncQueue, RemoteSerializer remoteSerializer, FirestoreChannel firestoreChannel) {
        this.workerQueue = asyncQueue;
        this.serializer = remoteSerializer;
        this.channel = firestoreChannel;
    }

    public static boolean isMissingSslCiphers(r0 r0Var) {
        q0 q0Var = r0Var.f19949a;
        Throwable th = r0Var.f19951c;
        if (!(th instanceof SSLHandshakeException)) {
            return false;
        }
        th.getMessage().contains("no ciphers available");
        return false;
    }

    public static boolean isPermanentError(FirebaseFirestoreException.Code code) {
        switch (AnonymousClass2.$SwitchMap$com$google$firebase$firestore$FirebaseFirestoreException$Code[code.ordinal()]) {
            case 1:
                throw new IllegalArgumentException("Treated status OK as error");
            case 2:
            case 3:
            case 4:
            case 5:
            case 6:
            case 7:
            case 8:
                return false;
            case 9:
            case 10:
            case 11:
            case 12:
            case 13:
            case 14:
            case 15:
            case 16:
            case 17:
                return true;
            default:
                throw new IllegalArgumentException("Unknown gRPC status code: " + code);
        }
    }

    public static boolean isPermanentWriteError(r0 r0Var) {
        return isPermanentError(r0Var) && !r0Var.f19949a.equals(q0.ABORTED);
    }

    /* JADX INFO: Access modifiers changed from: private */
    public /* synthetic */ List lambda$commit$0(Task task) throws Exception {
        if (!task.isSuccessful()) {
            if ((task.getException() instanceof FirebaseFirestoreException) && ((FirebaseFirestoreException) task.getException()).getCode() == FirebaseFirestoreException.Code.UNAUTHENTICATED) {
                this.channel.invalidateToken();
            }
            throw task.getException();
        }
        C1993m c1993m = (C1993m) task.getResult();
        SnapshotVersion snapshotVersionDecodeVersion = this.serializer.decodeVersion(c1993m.f());
        int i6 = c1993m.i();
        ArrayList arrayList = new ArrayList(i6);
        for (int i7 = 0; i7 < i6; i7++) {
            arrayList.add(this.serializer.decodeMutationResult(c1993m.h(i7), snapshotVersionDecodeVersion));
        }
        return arrayList;
    }

    /* JADX INFO: Access modifiers changed from: private */
    public /* synthetic */ Map lambda$runAggregateQuery$1(HashMap map, Task task) throws Exception {
        if (!task.isSuccessful()) {
            if ((task.getException() instanceof FirebaseFirestoreException) && ((FirebaseFirestoreException) task.getException()).getCode() == FirebaseFirestoreException.Code.UNAUTHENTICATED) {
                this.channel.invalidateToken();
            }
            throw task.getException();
        }
        HashMap map2 = new HashMap();
        for (Map.Entry entry : ((O) task.getResult()).g().f().entrySet()) {
            Assert.hardAssert(map.containsKey(entry.getKey()), "%s not present in aliasMap", entry.getKey());
            map2.put((String) map.get(entry.getKey()), (H0) entry.getValue());
        }
        return map2;
    }

    public Task<List<MutationResult>> commit(List<Mutation> list) {
        C1989k c1989kI = C1991l.i();
        c1989kI.d(this.serializer.databaseName());
        Iterator<Mutation> it = list.iterator();
        while (it.hasNext()) {
            c1989kI.c(this.serializer.encodeMutation(it.next()));
        }
        FirestoreChannel firestoreChannel = this.channel;
        i0 i0VarB = C.f16281b;
        if (i0VarB == null) {
            synchronized (C.class) {
                try {
                    i0VarB = C.f16281b;
                    if (i0VarB == null) {
                        D dB = i0.b();
                        dB.f521d = h0.f19874a;
                        dB.f522e = i0.a("google.firestore.v1.Firestore", "Commit");
                        dB.f518a = true;
                        C1991l c1991lH = C1991l.h();
                        C1343z c1343z = AbstractC2890c.f24005a;
                        dB.f519b = new C2889b(c1991lH);
                        dB.f520c = new C2889b(C1993m.g());
                        i0VarB = dB.b();
                        C.f16281b = i0VarB;
                    }
                } finally {
                }
            }
        }
        return firestoreChannel.runRpc(i0VarB, (C1991l) c1989kI.m359build()).continueWith(this.workerQueue.getExecutor(), new i(this));
    }

    public WatchStream createWatchStream(WatchStream.Callback callback) {
        return new WatchStream(this.channel, this.workerQueue, this.serializer, callback);
    }

    public WriteStream createWriteStream(WriteStream.Callback callback) {
        return new WriteStream(this.channel, this.workerQueue, this.serializer, callback);
    }

    public AsyncQueue getWorkerQueue() {
        return this.workerQueue;
    }

    public Task<List<MutableDocument>> lookup(final List<DocumentKey> list) {
        C1979f c1979fI = C1981g.i();
        c1979fI.d(this.serializer.databaseName());
        Iterator<DocumentKey> it = list.iterator();
        while (it.hasNext()) {
            c1979fI.c(this.serializer.encodeKey(it.next()));
        }
        final ArrayList arrayList = new ArrayList();
        final TaskCompletionSource taskCompletionSource = new TaskCompletionSource();
        FirestoreChannel firestoreChannel = this.channel;
        i0 i0VarB = C.f16280a;
        if (i0VarB == null) {
            synchronized (C.class) {
                try {
                    i0VarB = C.f16280a;
                    if (i0VarB == null) {
                        D dB = i0.b();
                        dB.f521d = h0.f19875b;
                        dB.f522e = i0.a("google.firestore.v1.Firestore", "BatchGetDocuments");
                        dB.f518a = true;
                        C1981g c1981gH = C1981g.h();
                        C1343z c1343z = AbstractC2890c.f24005a;
                        dB.f519b = new C2889b(c1981gH);
                        dB.f520c = new C2889b(C1983h.f());
                        i0VarB = dB.b();
                        C.f16280a = i0VarB;
                    }
                } finally {
                }
            }
        }
        firestoreChannel.runStreamingResponseRpc(i0VarB, (C1981g) c1979fI.m359build(), new FirestoreChannel.StreamingListener<C1983h>() { // from class: com.google.firebase.firestore.remote.Datastore.1
            @Override // com.google.firebase.firestore.remote.FirestoreChannel.StreamingListener
            public void onClose(r0 r0Var) {
                if (r0Var.e()) {
                    taskCompletionSource.trySetResult(Collections.EMPTY_LIST);
                    return;
                }
                FirebaseFirestoreException firebaseFirestoreExceptionExceptionFromStatus = Util.exceptionFromStatus(r0Var);
                if (firebaseFirestoreExceptionExceptionFromStatus.getCode() == FirebaseFirestoreException.Code.UNAUTHENTICATED) {
                    Datastore.this.channel.invalidateToken();
                }
                taskCompletionSource.trySetException(firebaseFirestoreExceptionExceptionFromStatus);
            }

            @Override // com.google.firebase.firestore.remote.FirestoreChannel.StreamingListener
            public void onMessage(C1983h c1983h) {
                arrayList.add(c1983h);
                if (arrayList.size() == list.size()) {
                    HashMap map = new HashMap();
                    Iterator it2 = arrayList.iterator();
                    while (it2.hasNext()) {
                        MutableDocument mutableDocumentDecodeMaybeDocument = Datastore.this.serializer.decodeMaybeDocument((C1983h) it2.next());
                        map.put(mutableDocumentDecodeMaybeDocument.getKey(), mutableDocumentDecodeMaybeDocument);
                    }
                    ArrayList arrayList2 = new ArrayList();
                    Iterator it3 = list.iterator();
                    while (it3.hasNext()) {
                        arrayList2.add((MutableDocument) map.get((DocumentKey) it3.next()));
                    }
                    taskCompletionSource.trySetResult(arrayList2);
                }
            }
        });
        return taskCompletionSource.getTask();
    }

    public Task<Map<String, H0>> runAggregateQuery(Query query, List<AggregateField> list) {
        z0 z0VarEncodeQueryTarget = this.serializer.encodeQueryTarget(query.toAggregateTarget());
        HashMap<String, String> map = new HashMap<>();
        Y yEncodeStructuredAggregationQuery = this.serializer.encodeStructuredAggregationQuery(z0VarEncodeQueryTarget, list, map);
        M mI = N.i();
        mI.c(z0VarEncodeQueryTarget.i());
        mI.d(yEncodeStructuredAggregationQuery);
        FirestoreChannel firestoreChannel = this.channel;
        i0 i0VarB = C.f16282c;
        if (i0VarB == null) {
            synchronized (C.class) {
                try {
                    i0VarB = C.f16282c;
                    if (i0VarB == null) {
                        D dB = i0.b();
                        dB.f521d = h0.f19875b;
                        dB.f522e = i0.a("google.firestore.v1.Firestore", "RunAggregationQuery");
                        dB.f518a = true;
                        N nH = N.h();
                        C1343z c1343z = AbstractC2890c.f24005a;
                        dB.f519b = new C2889b(nH);
                        dB.f520c = new C2889b(O.f());
                        i0VarB = dB.b();
                        C.f16282c = i0VarB;
                    }
                } finally {
                }
            }
        }
        return firestoreChannel.runRpc(i0VarB, (N) mI.m359build()).continueWith(this.workerQueue.getExecutor(), new e(0, this, map));
    }

    public void shutdown() {
        this.channel.shutdown();
    }

    public static boolean isPermanentError(r0 r0Var) {
        return isPermanentError(FirebaseFirestoreException.Code.fromValue(r0Var.f19949a.f19933a));
    }
}
