package com.atmob.voiceai.sdk.billing.operation;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.android.billingclient.api.BillingClient;
import com.android.billingclient.api.ProductDetails;
import com.android.billingclient.api.Purchase;
import com.android.billingclient.api.QueryProductDetailsParams;
import com.android.billingclient.api.QueryPurchasesParams;
import com.android.billingclient.api.SkuDetails;
import com.android.billingclient.api.SkuDetailsParams;
import com.atmob.common.logging.AtmobLog;
import com.atmob.voiceai.sdk.billing.bean.GPProductInfo;

import java.util.Collections;
import java.util.List;
import java.util.Objects;

import atmob.reactivex.rxjava3.core.Single;

public class QueryDetails {

    private static final String TAG = QueryDetails.class.getSimpleName();


    public static Single<GPProductInfo> queryGoodsDetails(BillingClient billingClient, String productType, @NonNull String productId, @Nullable String basePlanId, @Nullable String legacyProductId) {
        if (billingClient.isFeatureSupported(BillingClient.FeatureType.PRODUCT_DETAILS).getResponseCode() == BillingClient.BillingResponseCode.OK) {
            return queryProductDetails(billingClient, productType, productId, basePlanId);
        } else {
            return querySkuDetails(billingClient, productType, productId, basePlanId, legacyProductId);
        }
    }

    private static Single<GPProductInfo> queryProductDetails(BillingClient billingClient, String productType, @NonNull String productId, @Nullable String basePlanId) {
        AtmobLog.i(TAG, "querySkuDetails() called with: productType = [" + productType + "], productId = [" + productId + "], basePlanId = [" + basePlanId + "]");
        QueryProductDetailsParams productDetailsParams = QueryProductDetailsParams.newBuilder()
                .setProductList(Collections.singletonList(QueryProductDetailsParams.Product.newBuilder()
                        .setProductType(productType)
                        .setProductId(productId)
                        .build()))
                .build();
        return Single.create(emitter ->
                billingClient.queryProductDetailsAsync(productDetailsParams, (billingResult, list) -> {
                    AtmobLog.d(TAG, "onProductDetailsResponse() called with: billingResult = [" + billingResult + "], list = [" + list + "]");
                    if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) {
                        if (!list.isEmpty()) {
                            ProductDetails productDetails = list.get(0);
                            String price = "";
                            long amount = 0;
                            ProductDetails.SubscriptionOfferDetails subscriptionOfferDetails = getSubscriptionOfferDetails(productDetails, basePlanId);
                            if (subscriptionOfferDetails != null) {
                                List<ProductDetails.PricingPhase> pricingPhaseList = subscriptionOfferDetails.getPricingPhases().getPricingPhaseList();
                                ProductDetails.PricingPhase pricingPhase = pricingPhaseList.get(pricingPhaseList.size() - 1);
                                price = pricingPhase.getFormattedPrice();
                                amount = pricingPhase.getPriceAmountMicros();
                            }
                            emitter.onSuccess(new GPProductInfo(price, amount, productDetails));
                        } else {
                            emitter.onError(new IllegalStateException("Failed to query sku details, empty list"));
                        }
                    } else {
                        emitter.onError(new IllegalStateException("Failed to query sku details, billingResult: " + billingResult));
                    }
                }));
    }


    private static ProductDetails.SubscriptionOfferDetails getSubscriptionOfferDetails(ProductDetails details, String basePlanId) {
        if (details.getSubscriptionOfferDetails() == null || details.getSubscriptionOfferDetails().isEmpty())
            return null;
        for (ProductDetails.SubscriptionOfferDetails subscriptionOfferDetail : details.getSubscriptionOfferDetails()) {
            if (Objects.equals(subscriptionOfferDetail.getBasePlanId(), basePlanId)) {
                return subscriptionOfferDetail;
            }
        }
        return null;
    }

    private static Single<GPProductInfo> querySkuDetails(BillingClient billingClient, String productType, @NonNull String productId, @Nullable String basePlanId, @Nullable String legacyProductId) {
        AtmobLog.i(TAG, "querySkuDetails() called with: productType = [" + productType + "], productId = [" + productId + "], legacyProductId = [" + legacyProductId + "]");
        SkuDetailsParams detailsParams = SkuDetailsParams.newBuilder()
                .setType(productType)
                .setSkusList(Collections.singletonList(legacyProductId != null ? legacyProductId : productId))
                .build();
        return Single.create(emitter -> billingClient.querySkuDetailsAsync(detailsParams, (billingResult, list) -> {
            AtmobLog.d(TAG, "onSkuDetailsResponse() called with: billingResult = [" + billingResult + "], list = [" + list + "]");
            if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) {
                if (list != null && !list.isEmpty()) {
                    SkuDetails skuDetails = list.get(0);
                    emitter.onSuccess(new GPProductInfo(skuDetails.getPrice(), skuDetails.getPriceAmountMicros(), skuDetails));
                } else {
                    emitter.onError(new IllegalStateException("Failed to query sku details, empty list"));
                }
            } else {
                emitter.onError(new IllegalStateException("Failed to query sku details, billingResult: " + billingResult));
            }
        }));
    }

}
