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

import com.android.billingclient.api.BillingClient;
import com.android.billingclient.api.Purchase;
import com.android.billingclient.api.QueryPurchasesParams;
import com.atmob.common.logging.AtmobLog;

import java.util.List;

import atmob.reactivex.rxjava3.core.Single;

public class Purchases {

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

    public static Single<List<Purchase>> queryPurchase(BillingClient billingClient, @BillingClient.ProductType String productType) {
        return Single.create(emitter -> billingClient.queryPurchasesAsync(
                QueryPurchasesParams.newBuilder()
                        .setProductType(productType)
                        .build(),
                (billingResult, list) -> {
                    AtmobLog.d(TAG, "Query purchase finished with result: " + billingResult.getResponseCode() + " " + billingResult.getDebugMessage());
                    if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) {
                        AtmobLog.d(TAG, "Query purchase finished with result: " + list);
                        emitter.onSuccess(list);
                    } else {
                        emitter.onError(new Exception("Query purchase failed with result: " + billingResult.getResponseCode() + " " + billingResult.getDebugMessage()));
                    }
                }
        ));
    }
}
