package com.revenuecat.purchases.paywalls;

import A4.d;
import B4.a;
import C4.e;
import C4.j;
import E3.v;
import J4.c;
import S4.w;
import V4.C;
import V4.D0;
import V4.E;
import V4.N;
import a.AbstractC0872a;
import android.content.Context;
import android.support.v4.media.session.b;
import com.revenuecat.purchases.LogHandler;
import com.revenuecat.purchases.LogLevel;
import com.revenuecat.purchases.UiConfig;
import com.revenuecat.purchases.common.Config;
import com.revenuecat.purchases.common.LogWrapperKt;
import com.revenuecat.purchases.paywalls.fonts.DownloadableFontInfo;
import com.revenuecat.purchases.paywalls.fonts.DownloadableFontInfoKt;
import com.revenuecat.purchases.utils.DefaultUrlConnectionFactory;
import com.revenuecat.purchases.utils.Result;
import com.revenuecat.purchases.utils.UrlConnection;
import com.revenuecat.purchases.utils.UrlConnectionFactory;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import kotlin.jvm.internal.o;
import kotlin.jvm.internal.p;
import m1.g;
import m3.AbstractC2467b;
import n2.AbstractC2612c;
import w4.C3137A;
import w4.h;
import w4.i;
import w4.m;
import w4.n;
import x4.AbstractC3229F;
import x4.AbstractC3250p;
import x4.AbstractC3251q;
import x4.C3224A;

/* JADX INFO: loaded from: classes3.dex */
public final class FontLoader {
    private final h cacheDirectory$delegate;
    private final Map<String, DownloadedFontFamily> cachedFontFamilyByFamilyName;
    private final Map<DownloadableFontInfo, String> cachedFontFamilyByFontInfo;
    private final Context context;
    private final Map<String, Set<DownloadableFontInfo>> fontInfosForHash;
    private AtomicBoolean hasCheckedFoldersExist;
    private final C ioScope;
    private final Object lock;
    private final h md$delegate;
    private final File providedCacheDir;
    private final UrlConnectionFactory urlConnectionFactory;

    /* JADX INFO: renamed from: com.revenuecat.purchases.paywalls.FontLoader$md5Hex$1, reason: invalid class name */
    public static final class AnonymousClass1 extends p implements c {
        public static final AnonymousClass1 INSTANCE = new AnonymousClass1();

        public AnonymousClass1() {
            super(1);
        }

        public final CharSequence invoke(byte b5) {
            return String.format("%02x", Arrays.copyOf(new Object[]{Byte.valueOf(b5)}, 1));
        }

        @Override // J4.c
        public /* bridge */ /* synthetic */ Object invoke(Object obj) {
            return invoke(((Number) obj).byteValue());
        }
    }

    /* JADX INFO: renamed from: com.revenuecat.purchases.paywalls.FontLoader$startFontDownload$1, reason: invalid class name and case insensitive filesystem */
    @e(c = "com.revenuecat.purchases.paywalls.FontLoader$startFontDownload$1", f = "FontLoader.kt", l = {}, m = "invokeSuspend")
    public static final class C14391 extends j implements J4.e {
        final /* synthetic */ String $expectedMd5;
        final /* synthetic */ DownloadableFontInfo $fontInfo;
        final /* synthetic */ String $url;
        int label;

        /* JADX WARN: 'super' call moved to the top of the method (can break code semantics) */
        public C14391(String str, String str2, DownloadableFontInfo downloadableFontInfo, d dVar) {
            super(2, dVar);
            this.$url = str;
            this.$expectedMd5 = str2;
            this.$fontInfo = downloadableFontInfo;
        }

        @Override // C4.a
        public final d create(Object obj, d dVar) {
            return FontLoader.this.new C14391(this.$url, this.$expectedMd5, this.$fontInfo, dVar);
        }

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

        @Override // C4.a
        public final Object invokeSuspend(Object obj) {
            Object obj2;
            FontLoader fontLoader;
            a aVar = a.f492a;
            if (this.label != 0) {
                throw new IllegalStateException("call to 'resume' before 'invoke' with coroutine");
            }
            AbstractC2467b.l(obj);
            File cacheDirectory = FontLoader.this.getCacheDirectory();
            if (cacheDirectory == null) {
                LogWrapperKt.getCurrentLogHandler().e("[Purchases] - ERROR", "Cannot download font: cache directory is not available", null);
                return C3137A.f25453a;
            }
            if (!FontLoader.this.ensureFoldersExist(cacheDirectory)) {
                return C3137A.f25453a;
            }
            FontLoader fontLoader2 = FontLoader.this;
            byte[] bytes = this.$url.getBytes(S4.a.f6257a);
            o.g(bytes, "getBytes(...)");
            String strMd5Hex = fontLoader2.md5Hex(bytes);
            String strI1 = S4.p.i1('.', this.$url, "");
            File file = new File(cacheDirectory, strMd5Hex + '.' + strI1);
            Object obj3 = FontLoader.this.lock;
            FontLoader fontLoader3 = FontLoader.this;
            DownloadableFontInfo downloadableFontInfo = this.$fontInfo;
            String str = this.$url;
            synchronized (obj3) {
                Set set = (Set) fontLoader3.fontInfosForHash.get(strMd5Hex);
                if (set != null) {
                    LogLevel logLevel = LogLevel.VERBOSE;
                    LogHandler currentLogHandler = LogWrapperKt.getCurrentLogHandler();
                    if (Config.INSTANCE.getLogLevel().compareTo(logLevel) <= 0) {
                        currentLogHandler.v("[Purchases] - " + logLevel.name(), "Font download already in progress for " + str);
                    }
                    set.add(downloadableFontInfo);
                    return C3137A.f25453a;
                }
                Map map = fontLoader3.fontInfosForHash;
                LinkedHashSet linkedHashSet = new LinkedHashSet(AbstractC3229F.u(1));
                linkedHashSet.add(new DownloadableFontInfo[]{downloadableFontInfo}[0]);
                map.put(strMd5Hex, linkedHashSet);
                if (file.exists()) {
                    FontLoader.this.addFileToCache(strMd5Hex, file);
                    return C3137A.f25453a;
                }
                try {
                    Object objM532performDownloadAndCacheyxL6bBk = FontLoader.this.m532performDownloadAndCacheyxL6bBk(this.$url, this.$expectedMd5, strMd5Hex, strI1, cacheDirectory);
                    FontLoader fontLoader4 = FontLoader.this;
                    if (!(objM532performDownloadAndCacheyxL6bBk instanceof m)) {
                        fontLoader4.addFileToCache(strMd5Hex, (File) objM532performDownloadAndCacheyxL6bBk);
                    }
                    DownloadableFontInfo downloadableFontInfo2 = this.$fontInfo;
                    if (n.a(objM532performDownloadAndCacheyxL6bBk) != null) {
                        LogWrapperKt.getCurrentLogHandler().e("[Purchases] - ERROR", "Failed to download font for " + downloadableFontInfo2.getFamily(), null);
                    }
                    obj2 = FontLoader.this.lock;
                    fontLoader = FontLoader.this;
                } catch (Throwable th) {
                    try {
                        String str2 = this.$url;
                        LogWrapperKt.getCurrentLogHandler().e("[Purchases] - ERROR", "Error downloading remote font from " + str2, th);
                        obj2 = FontLoader.this.lock;
                        FontLoader fontLoader5 = FontLoader.this;
                        synchronized (obj2) {
                        }
                    } catch (Throwable th2) {
                        Object obj4 = FontLoader.this.lock;
                        FontLoader fontLoader6 = FontLoader.this;
                        synchronized (obj4) {
                            throw th2;
                        }
                    }
                }
                synchronized (obj2) {
                    return C3137A.f25453a;
                }
            }
        }
    }

    public FontLoader(Context context, File file, C ioScope, UrlConnectionFactory urlConnectionFactory) {
        o.h(context, "context");
        o.h(ioScope, "ioScope");
        o.h(urlConnectionFactory, "urlConnectionFactory");
        this.context = context;
        this.providedCacheDir = file;
        this.ioScope = ioScope;
        this.urlConnectionFactory = urlConnectionFactory;
        this.hasCheckedFoldersExist = new AtomicBoolean(false);
        this.cacheDirectory$delegate = g.j(i.f25465a, new FontLoader$cacheDirectory$2(this));
        this.md$delegate = g.k(FontLoader$md$2.INSTANCE);
        this.fontInfosForHash = new LinkedHashMap();
        this.lock = new Object();
        this.cachedFontFamilyByFontInfo = new LinkedHashMap();
        this.cachedFontFamilyByFamilyName = new LinkedHashMap();
    }

    /* JADX INFO: Access modifiers changed from: private */
    public final void addFileToCache(String str, File file) {
        synchronized (this.lock) {
            try {
                Set<DownloadableFontInfo> set = this.fontInfosForHash.get(str);
                if (set == null) {
                    set = C3224A.f26032a;
                }
                for (DownloadableFontInfo downloadableFontInfo : set) {
                    String family = downloadableFontInfo.getFamily();
                    if (this.cachedFontFamilyByFontInfo.get(downloadableFontInfo) != null) {
                        LogLevel logLevel = LogLevel.VERBOSE;
                        LogHandler currentLogHandler = LogWrapperKt.getCurrentLogHandler();
                        if (Config.INSTANCE.getLogLevel().compareTo(logLevel) <= 0) {
                            currentLogHandler.v("[Purchases] - " + logLevel.name(), "Font already cached for " + family + ". Skipping download.");
                        }
                    } else {
                        DownloadedFontFamily downloadedFontFamily = this.cachedFontFamilyByFamilyName.get(family);
                        if (downloadedFontFamily != null) {
                            this.cachedFontFamilyByFamilyName.put(family, new DownloadedFontFamily(downloadedFontFamily.getFamily(), AbstractC3251q.t0(downloadedFontFamily.getFonts(), new DownloadedFont(downloadableFontInfo.getWeight(), downloadableFontInfo.getStyle(), file))));
                            this.cachedFontFamilyByFontInfo.put(downloadableFontInfo, family);
                        } else {
                            DownloadedFontFamily downloadedFontFamily2 = new DownloadedFontFamily(family, AbstractC2612c.q(new DownloadedFont(downloadableFontInfo.getWeight(), downloadableFontInfo.getStyle(), file)));
                            this.cachedFontFamilyByFontInfo.put(downloadableFontInfo, family);
                            this.cachedFontFamilyByFamilyName.put(family, downloadedFontFamily2);
                        }
                    }
                }
                this.fontInfosForHash.remove(str);
            } catch (Throwable th) {
                throw th;
            }
        }
    }

    private final void downloadToFile(String str, File file) throws Throwable {
        UrlConnection urlConnectionCreateConnection$default;
        LogLevel logLevel = LogLevel.VERBOSE;
        LogHandler currentLogHandler = LogWrapperKt.getCurrentLogHandler();
        if (Config.INSTANCE.getLogLevel().compareTo(logLevel) <= 0) {
            currentLogHandler.v(com.google.android.recaptcha.internal.a.j(logLevel, new StringBuilder("[Purchases] - ")), "Downloading remote font from " + str);
        }
        UrlConnection urlConnection = null;
        try {
            urlConnectionCreateConnection$default = UrlConnectionFactory.createConnection$default(this.urlConnectionFactory, str, null, 2, null);
        } catch (Throwable th) {
            th = th;
        }
        try {
            if (urlConnectionCreateConnection$default.getResponseCode() != 200) {
                throw new IOException("HTTP " + urlConnectionCreateConnection$default.getResponseCode() + " when downloading paywall font: " + str);
            }
            InputStream inputStream = urlConnectionCreateConnection$default.getInputStream();
            try {
                writeStream(inputStream, file);
                b.j(inputStream, null);
                urlConnectionCreateConnection$default.disconnect();
            } finally {
            }
        } catch (Throwable th2) {
            th = th2;
            urlConnection = urlConnectionCreateConnection$default;
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
            throw th;
        }
    }

    /* JADX INFO: Access modifiers changed from: private */
    public final boolean ensureFoldersExist(File file) {
        boolean z6 = true;
        if (this.hasCheckedFoldersExist.get()) {
            return true;
        }
        if (file.exists() || file.mkdirs()) {
            if (!file.isDirectory()) {
                LogWrapperKt.getCurrentLogHandler().e("[Purchases] - ERROR", "Remote fonts cache path exists but is not a directory: " + file.getAbsolutePath(), null);
            }
            this.hasCheckedFoldersExist.set(z6);
            return z6;
        }
        LogWrapperKt.getCurrentLogHandler().e("[Purchases] - ERROR", "Unable to create cache directory for remote fonts: " + file.getAbsolutePath(), null);
        z6 = false;
        this.hasCheckedFoldersExist.set(z6);
        return z6;
    }

    /* JADX INFO: Access modifiers changed from: private */
    public final File getCacheDirectory() {
        return (File) this.cacheDirectory$delegate.getValue();
    }

    private final MessageDigest getMd() {
        Object value = this.md$delegate.getValue();
        o.g(value, "<get-md>(...)");
        return (MessageDigest) value;
    }

    /* JADX INFO: Access modifiers changed from: private */
    public final String md5Hex(byte[] bArr) {
        byte[] digest = getMd().digest(bArr);
        o.g(digest, "digest");
        return AbstractC3250p.Q(digest, "", AnonymousClass1.INSTANCE, 30);
    }

    /* JADX INFO: Access modifiers changed from: private */
    /* JADX INFO: renamed from: performDownloadAndCache-yxL6bBk, reason: not valid java name */
    public final Object m532performDownloadAndCacheyxL6bBk(String str, String str2, String str3, String str4, File file) throws Throwable {
        File file2 = new File(file, str3 + '.' + str4);
        StringBuilder sb = new StringBuilder(".");
        sb.append(str4);
        File tempFile = File.createTempFile("rc_paywall_font_download_", sb.toString(), file);
        try {
            o.g(tempFile, "tempFile");
            downloadToFile(str, tempFile);
            String strMd5Hex = md5Hex(H4.d.q0(tempFile));
            if (!w.t0(strMd5Hex, str2, true)) {
                tempFile.delete();
                LogWrapperKt.getCurrentLogHandler().e("[Purchases] - ERROR", "Downloaded font file is corrupt for " + str + ". expected=" + str2 + ", actual=" + strMd5Hex, null);
                return AbstractC2467b.d(new IOException("Downloaded font file is corrupt for " + str));
            }
            if (!tempFile.renameTo(file2)) {
                H4.d.p0(tempFile, file2);
                tempFile.delete();
            }
            LogLevel logLevel = LogLevel.DEBUG;
            LogHandler currentLogHandler = LogWrapperKt.getCurrentLogHandler();
            if (Config.INSTANCE.getLogLevel().compareTo(logLevel) <= 0) {
                currentLogHandler.d("[Purchases] - " + logLevel.name(), "Font downloaded successfully from " + str);
            }
            return file2;
        } catch (IOException e6) {
            if (tempFile.exists()) {
                tempFile.delete();
            }
            LogHandler currentLogHandler2 = LogWrapperKt.getCurrentLogHandler();
            StringBuilder sbS = com.google.android.recaptcha.internal.a.s("Error downloading font from ", str, ": ");
            sbS.append(e6.getMessage());
            currentLogHandler2.e("[Purchases] - ERROR", sbS.toString(), null);
            return AbstractC2467b.d(e6);
        }
    }

    private final void startFontDownload(DownloadableFontInfo downloadableFontInfo) {
        E.y(this.ioScope, null, null, new C14391(downloadableFontInfo.getUrl(), downloadableFontInfo.getExpectedMd5(), downloadableFontInfo, null), 3);
    }

    private final void writeStream(InputStream inputStream, File file) throws IOException {
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        try {
            byte[] bArr = new byte[8192];
            while (true) {
                int i6 = inputStream.read(bArr);
                if (i6 < 0) {
                    fileOutputStream.close();
                    return;
                }
                fileOutputStream.write(bArr, 0, i6);
            }
        } finally {
        }
    }

    public final DownloadedFontFamily getCachedFontFamilyOrStartDownload(UiConfig.AppConfig.FontsConfig.FontInfo.Name fontInfo) {
        o.h(fontInfo, "fontInfo");
        Result downloadableFontInfo = DownloadableFontInfoKt.toDownloadableFontInfo(fontInfo);
        if (!(downloadableFontInfo instanceof Result.Success)) {
            if (!(downloadableFontInfo instanceof Result.Error)) {
                throw new v();
            }
            LogWrapperKt.getCurrentLogHandler().e("[Purchases] - ERROR", (String) ((Result.Error) downloadableFontInfo).getValue(), null);
            return null;
        }
        DownloadableFontInfo downloadableFontInfo2 = (DownloadableFontInfo) ((Result.Success) downloadableFontInfo).getValue();
        synchronized (this.lock) {
            DownloadedFontFamily downloadedFontFamily = this.cachedFontFamilyByFamilyName.get(this.cachedFontFamilyByFontInfo.get(downloadableFontInfo2));
            if (downloadedFontFamily != null) {
                return downloadedFontFamily;
            }
            startFontDownload(downloadableFontInfo2);
            return null;
        }
    }

    /* JADX WARN: Illegal instructions before constructor call */
    public FontLoader(Context context, File file, C c6, UrlConnectionFactory urlConnectionFactory, int i6, kotlin.jvm.internal.h hVar) {
        file = (i6 & 2) != 0 ? null : file;
        if ((i6 & 4) != 0) {
            D0 d0D = E.d();
            c5.e eVar = N.f8259a;
            c6 = E.c(AbstractC0872a.a0(d0D, c5.d.f13466b));
        }
        this(context, file, c6, (i6 & 8) != 0 ? new DefaultUrlConnectionFactory() : urlConnectionFactory);
    }
}
