package com.amplifyframework.api.aws;

import android.annotation.SuppressLint;
import com.amplifyframework.api.ApiException;
import com.amplifyframework.api.aws.auth.ApiRequestDecoratorFactory;
import com.amplifyframework.api.graphql.GraphQLRequest;
import com.amplifyframework.api.graphql.GraphQLResponse;
import com.amplifyframework.core.Amplify;
import com.amplifyframework.core.Consumer;
import com.amplifyframework.core.category.CategoryType;
import com.amplifyframework.core.model.auth.AuthorizationTypeIterator;
import com.amplifyframework.datastore.appsync.AppSyncExtensions;
import com.amplifyframework.logging.Logger;
import com.amplifyframework.util.Empty;
import com.google.firebase.perf.network.FirebasePerfOkHttpClient;
import java.io.IOException;
import java.util.Objects;
import java.util.concurrent.ExecutorService;
import uq.b0;

/* loaded from: classes4.dex */
public final class MultiAuthAppSyncGraphQLOperation<R> extends AWSGraphQLOperation<R> {
    private static final String CONTENT_TYPE = "application/json";
    private static final Logger LOG = Amplify.Logging.logger(CategoryType.API, "amplify:aws-api");
    private final ApiRequestDecoratorFactory apiRequestDecoratorFactory;
    private AuthorizationTypeIterator authTypes;
    private final uq.z client;
    private final String endpoint;
    private final ExecutorService executorService;
    private final Consumer<ApiException> onFailure;
    private final Consumer<GraphQLResponse<R>> onResponse;
    private uq.e ongoingCall;

    /* loaded from: classes4.dex */
    public static final class Builder<R> {
        private String apiName;
        private ApiRequestDecoratorFactory apiRequestDecoratorFactory;
        private uq.z client;
        private String endpoint;
        private ExecutorService executorService;
        private Consumer<ApiException> onFailure;
        private Consumer<GraphQLResponse<R>> onResponse;
        private GraphQLRequest<R> request;
        private GraphQLResponse.Factory responseFactory;

        Builder() {
        }

        public Builder<R> apiName(String str) {
            this.apiName = str;
            return this;
        }

        public Builder<R> apiRequestDecoratorFactory(ApiRequestDecoratorFactory apiRequestDecoratorFactory) {
            this.apiRequestDecoratorFactory = apiRequestDecoratorFactory;
            return this;
        }

        @SuppressLint({"SyntheticAccessor"})
        public MultiAuthAppSyncGraphQLOperation<R> build() {
            return new MultiAuthAppSyncGraphQLOperation<>(this);
        }

        public Builder<R> client(uq.z zVar) {
            Objects.requireNonNull(zVar);
            this.client = zVar;
            return this;
        }

        public Builder<R> endpoint(String str) {
            Objects.requireNonNull(str);
            this.endpoint = str;
            return this;
        }

        public Builder<R> executorService(ExecutorService executorService) {
            this.executorService = executorService;
            return this;
        }

        public Builder<R> onFailure(Consumer<ApiException> consumer) {
            Objects.requireNonNull(consumer);
            this.onFailure = consumer;
            return this;
        }

        public Builder<R> onResponse(Consumer<GraphQLResponse<R>> consumer) {
            Objects.requireNonNull(consumer);
            this.onResponse = consumer;
            return this;
        }

        public Builder<R> request(GraphQLRequest<R> graphQLRequest) {
            Objects.requireNonNull(graphQLRequest);
            this.request = graphQLRequest;
            return this;
        }

        public Builder<R> responseFactory(GraphQLResponse.Factory factory) {
            Objects.requireNonNull(factory);
            this.responseFactory = factory;
            return this;
        }
    }

    @SuppressLint({"SyntheticAccessor"})
    /* loaded from: classes4.dex */
    public class OkHttpCallback implements uq.f {
        OkHttpCallback() {
        }

        @Override // uq.f
        public void onFailure(uq.e eVar, IOException iOException) {
            MultiAuthAppSyncGraphQLOperation.this.onFailure.accept(new ApiException("OkHttp client request failed.", iOException, "See attached exception for more details."));
        }

        @Override // uq.f
        public void onResponse(uq.e eVar, uq.d0 d0Var) {
            String j10;
            uq.e0 b10 = d0Var.b();
            if (b10 != null) {
                try {
                    j10 = b10.j();
                } catch (IOException e10) {
                    MultiAuthAppSyncGraphQLOperation.this.onFailure.accept(new ApiException("Could not retrieve the response body from the returned JSON", e10, "Sorry, we don’t have a recovery suggestion for this error."));
                    return;
                }
            } else {
                j10 = null;
            }
            try {
                GraphQLResponse<R> wrapResponse = MultiAuthAppSyncGraphQLOperation.this.wrapResponse(j10);
                if (!wrapResponse.hasErrors() || !MultiAuthAppSyncGraphQLOperation.this.hasAuthRelatedErrors(wrapResponse)) {
                    MultiAuthAppSyncGraphQLOperation.this.onResponse.accept(wrapResponse);
                } else {
                    if (!MultiAuthAppSyncGraphQLOperation.this.authTypes.hasNext()) {
                        MultiAuthAppSyncGraphQLOperation.this.onFailure.accept(new ApiException.ApiAuthException("Unable to successfully complete request with any of the compatible auth types.", "Check your application logs for detail."));
                        return;
                    }
                    ExecutorService executorService = MultiAuthAppSyncGraphQLOperation.this.executorService;
                    final MultiAuthAppSyncGraphQLOperation multiAuthAppSyncGraphQLOperation = MultiAuthAppSyncGraphQLOperation.this;
                    executorService.submit(new Runnable() { // from class: com.amplifyframework.api.aws.m
                        @Override // java.lang.Runnable
                        public final void run() {
                            MultiAuthAppSyncGraphQLOperation.f(MultiAuthAppSyncGraphQLOperation.this);
                        }
                    });
                }
            } catch (ApiException e11) {
                MultiAuthAppSyncGraphQLOperation.this.onFailure.accept(e11);
            }
        }
    }

    /* synthetic */ MultiAuthAppSyncGraphQLOperation(Builder builder, n nVar) {
        this(builder);
    }

    public static <R> Builder<R> builder() {
        return new Builder<>();
    }

    public void dispatchRequest() {
        if (!this.authTypes.hasNext()) {
            this.onFailure.accept(new ApiException.ApiAuthException("Unable to successfully complete request with any of the compatible auth types.", "Check your application logs for detail."));
            return;
        }
        AuthorizationType next = this.authTypes.next();
        try {
            uq.b0 decorate = this.apiRequestDecoratorFactory.forAuthType(next).decorate(new b0.a().y(this.endpoint).a("accept", CONTENT_TYPE).a("content-type", CONTENT_TYPE).q(uq.c0.c(((GraphQLRequest) getRequest()).getContent(), uq.x.g(CONTENT_TYPE))).b());
            LOG.debug("Request: " + ((GraphQLRequest) getRequest()).getContent());
            uq.e a10 = this.client.a(decorate);
            this.ongoingCall = a10;
            FirebasePerfOkHttpClient.enqueue(a10, new OkHttpCallback());
        } catch (ApiException e10) {
            LOG.warn("Failed to make a successful request with " + next, e10);
            if ((e10 instanceof ApiException.ApiAuthException) && this.authTypes.hasNext()) {
                this.executorService.submit(new l(this));
            } else {
                this.onFailure.accept(e10);
            }
        }
    }

    public static /* bridge */ /* synthetic */ void f(MultiAuthAppSyncGraphQLOperation multiAuthAppSyncGraphQLOperation) {
        multiAuthAppSyncGraphQLOperation.dispatchRequest();
    }

    public boolean hasAuthRelatedErrors(GraphQLResponse<R> graphQLResponse) {
        for (GraphQLResponse.Error error : graphQLResponse.getErrors()) {
            if (!Empty.check(error.getExtensions())) {
                return new AppSyncExtensions(error.getExtensions()).isUnauthorizedErrorType();
            }
        }
        return false;
    }

    @Override // com.amplifyframework.core.async.Cancelable
    public void cancel() {
        uq.e eVar = this.ongoingCall;
        if (eVar != null) {
            eVar.cancel();
        }
    }

    @Override // com.amplifyframework.core.async.AmplifyOperation
    public void start() {
        uq.e eVar = this.ongoingCall;
        if (eVar == null || !eVar.Q()) {
            this.executorService.submit(new l(this));
        }
    }

    private MultiAuthAppSyncGraphQLOperation(Builder<R> builder) {
        super(((Builder) builder).request, ((Builder) builder).responseFactory, ((Builder) builder).apiName);
        this.apiRequestDecoratorFactory = ((Builder) builder).apiRequestDecoratorFactory;
        this.endpoint = ((Builder) builder).endpoint;
        this.client = ((Builder) builder).client;
        this.onResponse = ((Builder) builder).onResponse;
        Consumer<ApiException> consumer = ((Builder) builder).onFailure;
        this.onFailure = consumer;
        this.executorService = ((Builder) builder).executorService;
        if (!(getRequest() instanceof AppSyncGraphQLRequest)) {
            consumer.accept(new ApiException("Multiauth only supported with AppSyncGraphQLRequest<T>.", "Sorry, we don’t have a recovery suggestion for this error."));
        } else {
            AppSyncGraphQLRequest appSyncGraphQLRequest = (AppSyncGraphQLRequest) getRequest();
            this.authTypes = MultiAuthModeStrategy.getInstance().authTypesFor(appSyncGraphQLRequest.getModelSchema(), appSyncGraphQLRequest.getAuthRuleOperation());
        }
    }
}
