package com.revenuecat.purchases.blockstore;

import A4.d;
import A4.l;
import C4.e;
import C4.j;
import J4.c;
import V4.C;
import V4.D0;
import V4.E;
import V4.N;
import a.AbstractC0872a;
import a5.m;
import android.content.Context;
import androidx.media3.container.MdtaMetadataEntry;
import com.google.android.gms.auth.blockstore.Blockstore;
import com.google.android.gms.auth.blockstore.BlockstoreClient;
import com.google.android.gms.auth.blockstore.DeleteBytesRequest;
import com.google.android.gms.auth.blockstore.RetrieveBytesRequest;
import com.google.android.gms.auth.blockstore.RetrieveBytesResponse;
import com.google.android.gms.auth.blockstore.StoreBytesData;
import com.google.android.gms.tasks.OnFailureListener;
import com.revenuecat.purchases.CustomerInfo;
import com.revenuecat.purchases.LogHandler;
import com.revenuecat.purchases.LogLevel;
import com.revenuecat.purchases.PurchasesException;
import com.revenuecat.purchases.common.Config;
import com.revenuecat.purchases.common.LogWrapperKt;
import com.revenuecat.purchases.identity.IdentityManager;
import java.util.Map;
import kotlin.jvm.internal.h;
import kotlin.jvm.internal.o;
import kotlin.jvm.internal.p;
import m3.AbstractC2467b;
import n2.AbstractC2612c;
import w4.C3137A;
import x4.z;

/* JADX INFO: loaded from: classes3.dex */
public final class BlockstoreHelper {

    @Deprecated
    public static final int BLOCKSTORE_MAX_ENTRIES = 16;

    @Deprecated
    public static final String BLOCKSTORE_USER_ID_KEY = "com.revenuecat.purchases.app_user_id";
    private static final Companion Companion = new Companion(null);
    private final BlockstoreClient blockstoreClient;
    private final IdentityManager identityManager;
    private final C ioScope;
    private final C mainScope;

    public static final class Companion {
        public /* synthetic */ Companion(h hVar) {
            this();
        }

        public final BlockstoreClient initializeBlockstoreClient(Context applicationContext) {
            o.h(applicationContext, "applicationContext");
            try {
                return Blockstore.getClient(applicationContext);
            } catch (NoClassDefFoundError e6) {
                LogWrapperKt.getCurrentLogHandler().e("[Purchases] - ERROR", "Cannot find Blockstore at runtime. Disabling automatic backups.", e6);
                return null;
            }
        }

        private Companion() {
        }
    }

    /* JADX INFO: renamed from: com.revenuecat.purchases.blockstore.BlockstoreHelper$aliasCurrentAndStoredUserIdsIfNeeded$1, reason: invalid class name */
    @e(c = "com.revenuecat.purchases.blockstore.BlockstoreHelper$aliasCurrentAndStoredUserIdsIfNeeded$1", f = "BlockstoreHelper.kt", l = {87, 100}, m = "invokeSuspend")
    public static final class AnonymousClass1 extends j implements J4.e {
        final /* synthetic */ J4.a $callback;
        final /* synthetic */ String $currentUserId;
        int label;

        /* JADX WARN: 'super' call moved to the top of the method (can break code semantics) */
        public AnonymousClass1(String str, J4.a aVar, d dVar) {
            super(2, dVar);
            this.$currentUserId = str;
            this.$callback = aVar;
        }

        @Override // C4.a
        public final d create(Object obj, d dVar) {
            return BlockstoreHelper.this.new AnonymousClass1(this.$currentUserId, this.$callback, dVar);
        }

        @Override // J4.e
        public final Object invoke(C c6, d dVar) {
            return ((AnonymousClass1) create(c6, dVar)).invokeSuspend(C3137A.f25453a);
        }

        /* JADX WARN: Code restructure failed: missing block: B:35:0x00a2, code lost:
        
            if (r10.aliasCurrentUserIdTo(r3, r9) == r2) goto L36;
         */
        @Override // C4.a
        /*
            Code decompiled incorrectly, please refer to instructions dump.
        */
        public final Object invokeSuspend(Object obj) {
            byte[] bytes;
            B4.a aVar = B4.a.f492a;
            int i6 = this.label;
            C3137A c3137a = C3137A.f25453a;
            try {
                try {
                    if (i6 == 0) {
                        AbstractC2467b.l(obj);
                        BlockstoreHelper blockstoreHelper = BlockstoreHelper.this;
                        this.label = 1;
                        obj = blockstoreHelper.getBlockstoreData(this);
                        if (obj == aVar) {
                        }
                        return aVar;
                    }
                    if (i6 != 1) {
                        if (i6 != 2) {
                            throw new IllegalStateException("call to 'resume' before 'invoke' with coroutine");
                        }
                        AbstractC2467b.l(obj);
                        BlockstoreHelper.aliasCurrentAndStoredUserIdsIfNeeded$callCompletion(BlockstoreHelper.this, this.$callback);
                        return c3137a;
                    }
                    AbstractC2467b.l(obj);
                    RetrieveBytesResponse.BlockstoreData blockstoreData = (RetrieveBytesResponse.BlockstoreData) ((Map) obj).get(BlockstoreHelper.BLOCKSTORE_USER_ID_KEY);
                    String str = (blockstoreData == null || (bytes = blockstoreData.getBytes()) == null) ? null : new String(bytes, S4.a.f6257a);
                    if (str == null || str.equals(this.$currentUserId)) {
                        BlockstoreHelper.aliasCurrentAndStoredUserIdsIfNeeded$callCompletion(BlockstoreHelper.this, this.$callback);
                        return c3137a;
                    }
                    LogLevel logLevel = LogLevel.DEBUG;
                    LogHandler currentLogHandler = LogWrapperKt.getCurrentLogHandler();
                    if (Config.INSTANCE.getLogLevel().compareTo(logLevel) <= 0) {
                        currentLogHandler.d("[Purchases] - " + logLevel.name(), "Aliasing Blockstore user ID: " + str + " with current UserID");
                    }
                    IdentityManager identityManager = BlockstoreHelper.this.identityManager;
                    this.label = 2;
                } catch (Exception e6) {
                    LogWrapperKt.getCurrentLogHandler().e("[Purchases] - ERROR", "Failed to retrieve Block store data. Will not recover userId. Error: " + e6.getMessage(), e6);
                    BlockstoreHelper.aliasCurrentAndStoredUserIdsIfNeeded$callCompletion(BlockstoreHelper.this, this.$callback);
                    return c3137a;
                }
            } catch (PurchasesException e7) {
                LogWrapperKt.getCurrentLogHandler().e("[Purchases] - ERROR", "Failed to alias Block store user ID: " + e7.getMessage() + ". Underlying error: " + e7.getUnderlyingErrorMessage() + ". Any purchases on previous anonymous user will not be recovered.", e7);
                BlockstoreHelper.aliasCurrentAndStoredUserIdsIfNeeded$callCompletion(BlockstoreHelper.this, this.$callback);
                return c3137a;
            }
        }
    }

    /* JADX INFO: renamed from: com.revenuecat.purchases.blockstore.BlockstoreHelper$clearUserIdBackupIfNeeded$1, reason: invalid class name and case insensitive filesystem */
    @e(c = "com.revenuecat.purchases.blockstore.BlockstoreHelper$clearUserIdBackupIfNeeded$1", f = "BlockstoreHelper.kt", l = {}, m = "invokeSuspend")
    public static final class C14041 extends j implements J4.e {
        final /* synthetic */ BlockstoreClient $blockstoreClient;
        final /* synthetic */ J4.a $callback;
        final /* synthetic */ DeleteBytesRequest $request;
        int label;

        /* JADX INFO: renamed from: com.revenuecat.purchases.blockstore.BlockstoreHelper$clearUserIdBackupIfNeeded$1$1, reason: invalid class name and collision with other inner class name */
        public static final class C00221 extends p implements c {
            final /* synthetic */ J4.a $callback;

            /* JADX WARN: 'super' call moved to the top of the method (can break code semantics) */
            public C00221(J4.a aVar) {
                super(1);
                this.$callback = aVar;
            }

            @Override // J4.c
            public /* bridge */ /* synthetic */ Object invoke(Object obj) {
                invoke((Boolean) obj);
                return C3137A.f25453a;
            }

            public final void invoke(Boolean bool) {
                LogLevel logLevel = LogLevel.DEBUG;
                LogHandler currentLogHandler = LogWrapperKt.getCurrentLogHandler();
                if (Config.INSTANCE.getLogLevel().compareTo(logLevel) <= 0) {
                    com.google.android.recaptcha.internal.a.u(logLevel, new StringBuilder("[Purchases] - "), currentLogHandler, "Block store cached UserID cleared if any");
                }
                this.$callback.invoke();
            }
        }

        /* JADX WARN: 'super' call moved to the top of the method (can break code semantics) */
        public C14041(BlockstoreClient blockstoreClient, DeleteBytesRequest deleteBytesRequest, J4.a aVar, d dVar) {
            super(2, dVar);
            this.$blockstoreClient = blockstoreClient;
            this.$request = deleteBytesRequest;
            this.$callback = aVar;
        }

        /* JADX INFO: Access modifiers changed from: private */
        public static final void invokeSuspend$lambda$2(J4.a aVar, Exception exc) {
            LogWrapperKt.getCurrentLogHandler().e("[Purchases] - ERROR", "Tried to clear Block store cached UserID but failed: " + exc.getMessage(), exc);
            aVar.invoke();
        }

        @Override // C4.a
        public final d create(Object obj, d dVar) {
            return new C14041(this.$blockstoreClient, this.$request, this.$callback, dVar);
        }

        @Override // J4.e
        public final Object invoke(C c6, d dVar) {
            return ((C14041) create(c6, dVar)).invokeSuspend(C3137A.f25453a);
        }

        @Override // C4.a
        public final Object invokeSuspend(Object obj) {
            B4.a aVar = B4.a.f492a;
            if (this.label != 0) {
                throw new IllegalStateException("call to 'resume' before 'invoke' with coroutine");
            }
            AbstractC2467b.l(obj);
            this.$blockstoreClient.deleteBytes(this.$request).addOnSuccessListener(new a(new C00221(this.$callback))).addOnFailureListener(new a(this.$callback));
            return C3137A.f25453a;
        }
    }

    /* JADX INFO: renamed from: com.revenuecat.purchases.blockstore.BlockstoreHelper$storeUserIdIfNeeded$1, reason: invalid class name and case insensitive filesystem */
    @e(c = "com.revenuecat.purchases.blockstore.BlockstoreHelper$storeUserIdIfNeeded$1", f = "BlockstoreHelper.kt", l = {61, MdtaMetadataEntry.TYPE_INDICATOR_INT32}, m = "invokeSuspend")
    public static final class C14051 extends j implements J4.e {
        final /* synthetic */ String $currentUserId;
        int label;

        /* JADX WARN: 'super' call moved to the top of the method (can break code semantics) */
        public C14051(String str, d dVar) {
            super(2, dVar);
            this.$currentUserId = str;
        }

        @Override // C4.a
        public final d create(Object obj, d dVar) {
            return BlockstoreHelper.this.new C14051(this.$currentUserId, dVar);
        }

        @Override // J4.e
        public final Object invoke(C c6, d dVar) {
            return ((C14051) create(c6, dVar)).invokeSuspend(C3137A.f25453a);
        }

        /* JADX WARN: Code restructure failed: missing block: B:22:0x003e, code lost:
        
            if (r1.storeUserIdIfNeeded(r7, r5, r6) == r0) goto L23;
         */
        @Override // C4.a
        /*
            Code decompiled incorrectly, please refer to instructions dump.
        */
        public final Object invokeSuspend(Object obj) {
            B4.a aVar = B4.a.f492a;
            int i6 = this.label;
            C3137A c3137a = C3137A.f25453a;
            try {
                try {
                } catch (Exception e6) {
                    LogWrapperKt.getCurrentLogHandler().e("[Purchases] - ERROR", "Failed to store user Id in Block store: " + e6.getMessage(), e6);
                }
                if (i6 == 0) {
                    AbstractC2467b.l(obj);
                    BlockstoreHelper blockstoreHelper = BlockstoreHelper.this;
                    this.label = 1;
                    obj = blockstoreHelper.getBlockstoreData(this);
                    if (obj == aVar) {
                    }
                    return aVar;
                }
                if (i6 != 1) {
                    if (i6 != 2) {
                        throw new IllegalStateException("call to 'resume' before 'invoke' with coroutine");
                    }
                    AbstractC2467b.l(obj);
                    return c3137a;
                }
                AbstractC2467b.l(obj);
                Map map = (Map) obj;
                BlockstoreHelper blockstoreHelper2 = BlockstoreHelper.this;
                String str = this.$currentUserId;
                this.label = 2;
            } catch (Exception e7) {
                LogWrapperKt.getCurrentLogHandler().e("[Purchases] - ERROR", "Failed to retrieve Block store data. Will not store userId. Error: " + e7.getMessage(), e7);
                return c3137a;
            }
        }
    }

    public BlockstoreHelper(Context applicationContext, IdentityManager identityManager, BlockstoreClient blockstoreClient, C ioScope, C mainScope) {
        o.h(applicationContext, "applicationContext");
        o.h(identityManager, "identityManager");
        o.h(ioScope, "ioScope");
        o.h(mainScope, "mainScope");
        this.identityManager = identityManager;
        this.blockstoreClient = blockstoreClient;
        this.ioScope = ioScope;
        this.mainScope = mainScope;
    }

    /* JADX INFO: Access modifiers changed from: private */
    public static final void aliasCurrentAndStoredUserIdsIfNeeded$callCompletion(BlockstoreHelper blockstoreHelper, J4.a aVar) {
        E.y(blockstoreHelper.mainScope, null, null, new BlockstoreHelper$aliasCurrentAndStoredUserIdsIfNeeded$callCompletion$1(aVar, null), 3);
    }

    /* JADX INFO: Access modifiers changed from: private */
    public final Object getBlockstoreData(d dVar) {
        BlockstoreClient blockstoreClient = this.blockstoreClient;
        if (blockstoreClient == null) {
            return z.f26066a;
        }
        RetrieveBytesRequest retrieveBytesRequestBuild = new RetrieveBytesRequest.Builder().setRetrieveAll(true).build();
        o.g(retrieveBytesRequestBuild, "Builder()\n            .s…rue)\n            .build()");
        final l lVar = new l(AbstractC0872a.V(dVar));
        blockstoreClient.retrieveBytes(retrieveBytesRequestBuild).addOnSuccessListener(new BlockstoreHelper$sam$com_google_android_gms_tasks_OnSuccessListener$0(new BlockstoreHelper$getBlockstoreData$2$1(lVar))).addOnFailureListener(new OnFailureListener() { // from class: com.revenuecat.purchases.blockstore.BlockstoreHelper$getBlockstoreData$2$2
            @Override // com.google.android.gms.tasks.OnFailureListener
            public final void onFailure(Exception it) {
                o.h(it, "it");
                lVar.resumeWith(AbstractC2467b.d(it));
            }
        });
        Object objA = lVar.a();
        B4.a aVar = B4.a.f492a;
        return objA;
    }

    public final void aliasCurrentAndStoredUserIdsIfNeeded(J4.a callback) {
        o.h(callback, "callback");
        String currentAppUserID = this.identityManager.getCurrentAppUserID();
        if (IdentityManager.Companion.isUserIDAnonymous(currentAppUserID)) {
            E.y(this.ioScope, null, null, new AnonymousClass1(currentAppUserID, callback, null), 3);
        } else {
            aliasCurrentAndStoredUserIdsIfNeeded$callCompletion(this, callback);
        }
    }

    public final void clearUserIdBackupIfNeeded(J4.a callback) {
        o.h(callback, "callback");
        BlockstoreClient blockstoreClient = this.blockstoreClient;
        if (blockstoreClient == null) {
            callback.invoke();
            return;
        }
        DeleteBytesRequest deleteBytesRequestBuild = new DeleteBytesRequest.Builder().setKeys(AbstractC2612c.q(BLOCKSTORE_USER_ID_KEY)).build();
        o.g(deleteBytesRequestBuild, "Builder()\n            .s…EY))\n            .build()");
        E.y(this.ioScope, null, null, new C14041(blockstoreClient, deleteBytesRequestBuild, callback, null), 3);
    }

    public final void storeUserIdIfNeeded(CustomerInfo customerInfo) {
        o.h(customerInfo, "customerInfo");
        if (this.blockstoreClient == null) {
            return;
        }
        String currentAppUserID = this.identityManager.getCurrentAppUserID();
        if (!IdentityManager.Companion.isUserIDAnonymous(currentAppUserID) || customerInfo.getAllPurchasedProductIds().isEmpty()) {
            return;
        }
        E.y(this.ioScope, null, null, new C14051(currentAppUserID, null), 3);
    }

    /* JADX WARN: Illegal instructions before constructor call */
    public BlockstoreHelper(Context context, IdentityManager identityManager, BlockstoreClient blockstoreClient, C c6, C c7, int i6, h hVar) {
        BlockstoreClient blockstoreClientInitializeBlockstoreClient = (i6 & 4) != 0 ? Companion.initializeBlockstoreClient(context) : blockstoreClient;
        if ((i6 & 8) != 0) {
            D0 d0D = E.d();
            c5.e eVar = N.f8259a;
            c6 = E.c(AbstractC0872a.a0(d0D, c5.d.f13466b.i(1)));
        }
        C c8 = c6;
        if ((i6 & 16) != 0) {
            D0 d0D2 = E.d();
            c5.e eVar2 = N.f8259a;
            c7 = E.c(AbstractC0872a.a0(d0D2, m.f10845a));
        }
        this(context, identityManager, blockstoreClientInitializeBlockstoreClient, c8, c7);
    }

    /* JADX INFO: Access modifiers changed from: private */
    public final Object storeUserIdIfNeeded(Map<String, ? extends RetrieveBytesResponse.BlockstoreData> map, String str, d dVar) {
        BlockstoreClient blockstoreClient = this.blockstoreClient;
        C3137A c3137a = C3137A.f25453a;
        if (blockstoreClient == null) {
            return c3137a;
        }
        if (map.get(BLOCKSTORE_USER_ID_KEY) != null) {
            LogLevel logLevel = LogLevel.DEBUG;
            LogHandler currentLogHandler = LogWrapperKt.getCurrentLogHandler();
            if (Config.INSTANCE.getLogLevel().compareTo(logLevel) <= 0) {
                com.google.android.recaptcha.internal.a.u(logLevel, new StringBuilder("[Purchases] - "), currentLogHandler, "Block store: Not storing user id since there is one already present.");
            }
            return c3137a;
        }
        if (map.size() >= 16) {
            LogLevel logLevel2 = LogLevel.DEBUG;
            LogHandler currentLogHandler2 = LogWrapperKt.getCurrentLogHandler();
            if (Config.INSTANCE.getLogLevel().compareTo(logLevel2) <= 0) {
                com.google.android.recaptcha.internal.a.u(logLevel2, new StringBuilder("[Purchases] - "), currentLogHandler2, "Block store: Not storing user id since block store is already full.");
            }
            return c3137a;
        }
        LogLevel logLevel3 = LogLevel.DEBUG;
        LogHandler currentLogHandler3 = LogWrapperKt.getCurrentLogHandler();
        if (Config.INSTANCE.getLogLevel().compareTo(logLevel3) <= 0) {
            currentLogHandler3.d(com.google.android.recaptcha.internal.a.j(logLevel3, new StringBuilder("[Purchases] - ")), "Block store: Storing UserID: " + str + " in Block store.");
        }
        StoreBytesData.Builder builder = new StoreBytesData.Builder();
        byte[] bytes = str.getBytes(S4.a.f6257a);
        o.g(bytes, "getBytes(...)");
        StoreBytesData storeBytesDataBuild = builder.setBytes(bytes).setKey(BLOCKSTORE_USER_ID_KEY).setShouldBackupToCloud(true).build();
        o.g(storeBytesDataBuild, "Builder()\n            .s…rue)\n            .build()");
        final l lVar = new l(AbstractC0872a.V(dVar));
        blockstoreClient.storeBytes(storeBytesDataBuild).addOnSuccessListener(new BlockstoreHelper$sam$com_google_android_gms_tasks_OnSuccessListener$0(new BlockstoreHelper$storeUserIdIfNeeded$6$1(lVar, str))).addOnFailureListener(new OnFailureListener() { // from class: com.revenuecat.purchases.blockstore.BlockstoreHelper$storeUserIdIfNeeded$6$2
            @Override // com.google.android.gms.tasks.OnFailureListener
            public final void onFailure(Exception it) {
                o.h(it, "it");
                lVar.resumeWith(AbstractC2467b.d(it));
            }
        });
        Object objA = lVar.a();
        return objA == B4.a.f492a ? objA : c3137a;
    }
}
