package com.google.firebase.firestore.remote;

import E3.v;
import android.content.Context;
import androidx.media3.common.C;
import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.android.gms.common.GooglePlayServicesRepairableException;
import com.google.android.gms.security.ProviderInstaller;
import com.google.android.gms.tasks.Task;
import com.google.android.gms.tasks.Tasks;
import com.google.firebase.firestore.core.DatabaseInfo;
import com.google.firebase.firestore.util.AsyncQueue;
import com.google.firebase.firestore.util.Executors;
import com.google.firebase.firestore.util.Logger;
import com.google.firebase.firestore.util.Supplier;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import k4.AbstractC2392e;
import k4.AbstractC2395h;
import k4.AbstractC2397j;
import k4.C2393f;
import k4.C2394g;
import k4.C2401n;
import k4.EnumC2404q;
import k4.W;
import k4.X;
import k4.Y;
import k4.Z;
import k4.a0;
import k4.i0;
import s4.AbstractC2917b;
import s4.EnumC2916a;

/* JADX INFO: loaded from: classes3.dex */
public class GrpcCallProvider {
    private static final int CONNECTIVITY_ATTEMPT_TIMEOUT_MS = 15000;
    private static final String LOG_TAG = "GrpcCallProvider";
    private static Supplier<X> overrideChannelBuilderSupplier;
    private final AsyncQueue asyncQueue;
    private C2394g callOptions;
    private Task<W> channelTask;
    private AsyncQueue.DelayedTask connectivityAttemptTimer;
    private final Context context;
    private final DatabaseInfo databaseInfo;
    private final AbstractC2392e firestoreHeaders;

    public GrpcCallProvider(AsyncQueue asyncQueue, Context context, DatabaseInfo databaseInfo, AbstractC2392e abstractC2392e) {
        this.asyncQueue = asyncQueue;
        this.context = context;
        this.databaseInfo = databaseInfo;
        this.firestoreHeaders = abstractC2392e;
        initChannelTask();
    }

    private void clearConnectivityAttemptTimer() {
        if (this.connectivityAttemptTimer != null) {
            Logger.debug(LOG_TAG, "Clearing the connectivityAttemptTimer", new Object[0]);
            this.connectivityAttemptTimer.cancel();
            this.connectivityAttemptTimer = null;
        }
    }

    private W initChannel(Context context, DatabaseInfo databaseInfo) {
        a0 a0Var;
        List list;
        X x6;
        try {
            ProviderInstaller.installIfNeeded(context);
        } catch (GooglePlayServicesNotAvailableException | GooglePlayServicesRepairableException | IllegalStateException e6) {
            Logger.warn(LOG_TAG, "Failed to update ssl context: %s", e6);
        }
        Supplier<X> supplier = overrideChannelBuilderSupplier;
        if (supplier != null) {
            x6 = supplier.get();
        } else {
            String host = databaseInfo.getHost();
            java.util.logging.Logger logger = a0.f19837c;
            synchronized (a0.class) {
                try {
                    if (a0.f19838d == null) {
                        List<Y> listE = AbstractC2395h.e(Y.class, a0.a(), Y.class.getClassLoader(), new C2401n(7));
                        a0.f19838d = new a0();
                        for (Y y6 : listE) {
                            a0.f19837c.fine("Service loader found " + y6);
                            a0 a0Var2 = a0.f19838d;
                            synchronized (a0Var2) {
                                y6.getClass();
                                a0Var2.f19839a.add(y6);
                            }
                        }
                        a0 a0Var3 = a0.f19838d;
                        synchronized (a0Var3) {
                            ArrayList arrayList = new ArrayList(a0Var3.f19839a);
                            Collections.sort(arrayList, Collections.reverseOrder(new Z()));
                            a0Var3.f19840b = Collections.unmodifiableList(arrayList);
                        }
                    }
                    a0Var = a0.f19838d;
                } catch (Throwable th) {
                    throw th;
                }
            }
            synchronized (a0Var) {
                list = a0Var.f19840b;
            }
            if ((list.isEmpty() ? null : (Y) list.get(0)) == null) {
                throw new v("No functional channel service provider found. Try adding a dependency on the grpc-okhttp, grpc-netty, or grpc-netty-shaded artifact");
            }
            n4.h hVar = new n4.h(host);
            if (!databaseInfo.isSslEnabled()) {
                hVar.f21672g = 2;
            }
            x6 = hVar;
        }
        TimeUnit timeUnit = TimeUnit.SECONDS;
        x6.b();
        l4.d dVar = new l4.d(x6);
        dVar.f20324b = context;
        return dVar.a();
    }

    private void initChannelTask() {
        this.channelTask = Tasks.call(Executors.BACKGROUND_EXECUTOR, new Callable() { // from class: com.google.firebase.firestore.remote.h
            @Override // java.util.concurrent.Callable
            public final Object call() {
                return this.f14129a.lambda$initChannelTask$6();
            }
        });
    }

    /* JADX INFO: Access modifiers changed from: private */
    public /* synthetic */ Task lambda$createClientCall$0(i0 i0Var, Task task) {
        return Tasks.forResult(((W) task.getResult()).l(i0Var, this.callOptions));
    }

    /* JADX INFO: Access modifiers changed from: private */
    public W lambda$initChannelTask$6() {
        W wInitChannel = initChannel(this.context, this.databaseInfo);
        this.asyncQueue.enqueueAndForget(new g(this, wInitChannel, 4));
        C2394g c2394gC = C2394g.f19857i.c(AbstractC2917b.f24214a, EnumC2916a.f24212a);
        A4.g.o(wInitChannel, "channel");
        AbstractC2392e abstractC2392e = this.firestoreHeaders;
        C2393f c2393fB = C2394g.b(c2394gC);
        c2393fB.f19851c = abstractC2392e;
        C2394g c2394g = new C2394g(c2393fB);
        Executor executor = this.asyncQueue.getExecutor();
        C2393f c2393fB2 = C2394g.b(c2394g);
        c2393fB2.f19850b = executor;
        this.callOptions = new C2394g(c2393fB2);
        Logger.debug(LOG_TAG, "Channel successfully reset.", new Object[0]);
        return wInitChannel;
    }

    /* JADX INFO: Access modifiers changed from: private */
    public /* synthetic */ void lambda$onConnectivityStateChange$1(W w6) {
        Logger.debug(LOG_TAG, "connectivityAttemptTimer elapsed. Resetting the channel.", new Object[0]);
        clearConnectivityAttemptTimer();
        resetChannel(w6);
    }

    /* JADX INFO: Access modifiers changed from: private */
    public /* synthetic */ void lambda$onConnectivityStateChange$3(W w6) {
        this.asyncQueue.enqueueAndForget(new g(this, w6, 2));
    }

    /* JADX INFO: Access modifiers changed from: private */
    public /* synthetic */ void lambda$resetChannel$4(W w6) {
        w6.x();
        initChannelTask();
    }

    /* JADX INFO: Access modifiers changed from: private */
    /* JADX INFO: renamed from: onConnectivityStateChange, reason: merged with bridge method [inline-methods] and merged with bridge method [inline-methods] */
    public void lambda$onConnectivityStateChange$2(W w6) {
        EnumC2404q enumC2404qU = w6.u();
        Logger.debug(LOG_TAG, "Current gRPC connectivity state: " + enumC2404qU, new Object[0]);
        clearConnectivityAttemptTimer();
        if (enumC2404qU == EnumC2404q.f19910a) {
            Logger.debug(LOG_TAG, "Setting the connectivityAttemptTimer", new Object[0]);
            this.connectivityAttemptTimer = this.asyncQueue.enqueueAfterDelay(AsyncQueue.TimerId.CONNECTIVITY_ATTEMPT_TIMER, C.DEFAULT_SEEK_FORWARD_INCREMENT_MS, new g(this, w6, 0));
        }
        w6.v(enumC2404qU, new g(this, w6, 1));
    }

    private void resetChannel(W w6) {
        this.asyncQueue.enqueueAndForget(new g(this, w6, 3));
    }

    public <ReqT, RespT> Task<AbstractC2397j> createClientCall(i0 i0Var) {
        return this.channelTask.continueWithTask(this.asyncQueue.getExecutor(), new e(1, this, i0Var));
    }

    public void shutdown() {
        try {
            W w6 = (W) Tasks.await(this.channelTask);
            w6.w();
            try {
                TimeUnit timeUnit = TimeUnit.SECONDS;
                if (w6.s(1L)) {
                    return;
                }
                Logger.debug("FirestoreChannel", "Unable to gracefully shutdown the gRPC ManagedChannel. Will attempt an immediate shutdown.", new Object[0]);
                w6.x();
                if (w6.s(60L)) {
                    return;
                }
                Logger.warn("FirestoreChannel", "Unable to forcefully shutdown the gRPC ManagedChannel.", new Object[0]);
            } catch (InterruptedException unused) {
                w6.x();
                Logger.warn("FirestoreChannel", "Interrupted while shutting down the gRPC Managed Channel", new Object[0]);
                Thread.currentThread().interrupt();
            }
        } catch (InterruptedException unused2) {
            Logger.warn("FirestoreChannel", "Interrupted while retrieving the gRPC Managed Channel", new Object[0]);
            Thread.currentThread().interrupt();
        } catch (ExecutionException e6) {
            Logger.warn("FirestoreChannel", "Channel is not initialized, shutdown will just do nothing. Channel initializing run into exception: %s", e6);
        }
    }
}
