package com.revenuecat.purchases.common;

import android.net.Uri;
import com.revenuecat.purchases.CustomerInfo;
import com.revenuecat.purchases.CustomerInfoOriginalSource;
import com.revenuecat.purchases.EntitlementInfos;
import com.revenuecat.purchases.SubscriptionInfo;
import com.revenuecat.purchases.VerificationResult;
import com.revenuecat.purchases.common.networking.HTTPResult;
import com.revenuecat.purchases.common.responses.CustomerInfoResponseJsonKeys;
import com.revenuecat.purchases.common.responses.SubscriptionInfoResponse;
import com.revenuecat.purchases.utils.Iso8601Utils;
import com.revenuecat.purchases.utils.JSONObjectExtensionsKt;
import com.revenuecat.purchases.utils.SerializationException;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import kotlin.jvm.internal.o;
import l5.AbstractC2458c;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import x4.AbstractC3229F;

/* JADX INFO: loaded from: classes3.dex */
public final class CustomerInfoFactory {
    public static final CustomerInfoFactory INSTANCE = new CustomerInfoFactory();

    private CustomerInfoFactory() {
    }

    public static /* synthetic */ CustomerInfo buildCustomerInfo$default(CustomerInfoFactory customerInfoFactory, JSONObject jSONObject, Date date, VerificationResult verificationResult, CustomerInfoOriginalSource customerInfoOriginalSource, boolean z6, int i6, Object obj) {
        if ((i6 & 8) != 0) {
            customerInfoOriginalSource = CustomerInfoOriginalSource.MAIN;
        }
        CustomerInfoOriginalSource customerInfoOriginalSource2 = customerInfoOriginalSource;
        if ((i6 & 16) != 0) {
            z6 = false;
        }
        return customerInfoFactory.buildCustomerInfo(jSONObject, date, verificationResult, customerInfoOriginalSource2, z6);
    }

    private final HashMap<String, Date> parseDates(JSONObject jSONObject, String str) throws JSONException {
        HashMap<String, Date> map = new HashMap<>();
        Iterator<String> itKeys = jSONObject.keys();
        while (itKeys.hasNext()) {
            String key = itKeys.next();
            String it = jSONObject.getJSONObject(key).optString("product_plan_identifier");
            o.g(it, "it");
            if (it.length() <= 0) {
                it = null;
            }
            JSONObject expirationObject = jSONObject.getJSONObject(key);
            if (it != null) {
                String str2 = key + ':' + it;
                if (str2 != null) {
                    key = str2;
                }
            }
            o.g(key, "key");
            o.g(expirationObject, "expirationObject");
            map.put(key, JSONObjectExtensionsKt.optDate(expirationObject, str));
        }
        return map;
    }

    private final Map<String, Date> parseExpirations(JSONObject jSONObject) {
        return parseDates(jSONObject, "expires_date");
    }

    private final Map<String, Date> parsePurchaseDates(JSONObject jSONObject) {
        return parseDates(jSONObject, "purchase_date");
    }

    public final CustomerInfo buildCustomerInfo(HTTPResult httpResult) {
        o.h(httpResult, "httpResult");
        return buildCustomerInfo(httpResult.getBody(), httpResult.getRequestDate(), httpResult.getVerificationResult(), httpResult.isLoadShedderResponse() ? CustomerInfoOriginalSource.LOAD_SHEDDER : CustomerInfoOriginalSource.MAIN, false);
    }

    public final Map<String, SubscriptionInfo> parseSubscriptionInfos(JSONObject subscriberJSONObject, Date requestDate) throws JSONException {
        o.h(subscriberJSONObject, "subscriberJSONObject");
        o.h(requestDate, "requestDate");
        LinkedHashMap linkedHashMap = new LinkedHashMap();
        JSONObject jSONObject = subscriberJSONObject.getJSONObject(CustomerInfoResponseJsonKeys.SUBSCRIPTIONS);
        try {
            Iterator<String> itKeys = jSONObject.keys();
            o.g(itKeys, "subscriptions.keys()");
            while (itKeys.hasNext()) {
                String productId = itKeys.next();
                JSONObject jSONObject2 = jSONObject.getJSONObject(productId);
                AbstractC2458c defaultJson = JsonProvider.Companion.getDefaultJson();
                String string = jSONObject2.toString();
                o.g(string, "subscriptionJSONObject.toString()");
                defaultJson.getClass();
                SubscriptionInfoResponse subscriptionInfoResponse = (SubscriptionInfoResponse) defaultJson.b(SubscriptionInfoResponse.Companion.serializer(), string);
                o.g(productId, "productId");
                Date date = requestDate;
                linkedHashMap.put(productId, new SubscriptionInfo(productId, date, subscriptionInfoResponse, null, 8, null));
                requestDate = date;
            }
        } catch (SerializationException e6) {
            LogWrapperKt.getCurrentLogHandler().e("[Purchases] - ERROR", "Error deserializing subscription information", e6);
        } catch (IllegalArgumentException e7) {
            LogWrapperKt.getCurrentLogHandler().e("[Purchases] - ERROR", "Error deserializing subscription information. The input is not a SubscriptionInfo", e7);
        }
        return linkedHashMap;
    }

    /* JADX WARN: Removed duplicated region for block: B:16:0x0093  */
    /*
        Code decompiled incorrectly, please refer to instructions dump.
    */
    public final CustomerInfo buildCustomerInfo(JSONObject body, Date date, VerificationResult verificationResult, CustomerInfoOriginalSource originalSource, boolean z6) throws JSONException {
        EntitlementInfos entitlementInfos;
        Date date2;
        o.h(body, "body");
        o.h(verificationResult, "verificationResult");
        o.h(originalSource, "originalSource");
        JSONObject jSONObject = body.getJSONObject(CustomerInfoResponseJsonKeys.SUBSCRIBER);
        JSONObject jSONObject2 = jSONObject.getJSONObject(CustomerInfoResponseJsonKeys.NON_SUBSCRIPTIONS);
        JSONObject jSONObject3 = new JSONObject();
        Iterator<String> itKeys = jSONObject2.keys();
        o.g(itKeys, "nonSubscriptions.keys()");
        while (itKeys.hasNext()) {
            String next = itKeys.next();
            JSONArray jSONArray = jSONObject2.getJSONArray(next);
            int length = jSONArray.length();
            if (length > 0) {
                jSONObject3.put(next, jSONArray.getJSONObject(length - 1));
            }
        }
        JSONObject subscriptions = jSONObject.getJSONObject(CustomerInfoResponseJsonKeys.SUBSCRIPTIONS);
        o.g(subscriptions, "subscriptions");
        Map<String, Date> expirations = parseExpirations(subscriptions);
        LinkedHashMap linkedHashMapZ = AbstractC3229F.z(parsePurchaseDates(subscriptions), parsePurchaseDates(jSONObject3));
        JSONObject jSONObjectOptJSONObject = jSONObject.optJSONObject(CustomerInfoResponseJsonKeys.ENTITLEMENTS);
        Date requestDate = date == null ? Iso8601Utils.parse(body.getString(CustomerInfoResponseJsonKeys.REQUEST_DATE)) : date;
        Date firstSeen = Iso8601Utils.parse(jSONObject.getString(CustomerInfoResponseJsonKeys.FIRST_SEEN));
        if (jSONObjectOptJSONObject != null) {
            o.g(requestDate, "requestDate");
            entitlementInfos = EntitlementInfoFactoriesKt.buildEntitlementInfos(jSONObjectOptJSONObject, subscriptions, jSONObject3, requestDate, verificationResult);
            if (entitlementInfos == null) {
                Map map = Collections.EMPTY_MAP;
                o.g(map, "emptyMap()");
                entitlementInfos = new EntitlementInfos(map, verificationResult);
            }
        }
        String strOptNullableString = JSONObjectExtensionsKt.optNullableString(jSONObject, "management_url");
        String strOptNullableString2 = JSONObjectExtensionsKt.optNullableString(jSONObject, "original_purchase_date");
        if (strOptNullableString2 == null || (date2 = Iso8601Utils.parse(strOptNullableString2)) == null) {
            date2 = null;
        }
        int iOptInt = body.optInt("schema_version", 3);
        String strOptString = jSONObject.optString(CustomerInfoResponseJsonKeys.ORIGINAL_APP_USER_ID);
        Uri uri = strOptNullableString != null ? Uri.parse(strOptNullableString) : null;
        o.g(requestDate, "requestDate");
        o.g(firstSeen, "firstSeen");
        o.g(strOptString, "optString(CustomerInfoRe…eys.ORIGINAL_APP_USER_ID)");
        return new CustomerInfo(entitlementInfos, expirations, linkedHashMapZ, requestDate, iOptInt, firstSeen, strOptString, uri, date2, body, originalSource, z6);
    }
}
