package com.zxhl.cms.googlepay

import android.util.Log
import android.view.View
import com.android.billingclient.api.*
import com.android.billingclient.api.BillingClient.SkuType
import com.zxhl.cms.AppContext
import com.zxhl.cms.R
import com.zxhl.cms.common.base.BaseActivity
import kotlinx.android.synthetic.main.activity_google_pay.*


class GooglePayActivity : BaseActivity() {
    private val TAG = "GooglePayActivity"
    private val purchasesUpdatedListener =
        PurchasesUpdatedListener { billingResult, purchases ->
            // To be implemented in a later section.
            Log.d(TAG, "purchasesUpdatedListener" + billingResult.responseCode)
            Log.d(TAG, "purchasesUpdatedListener" + purchases?.size)
        }

    private var billingClient = BillingClient.newBuilder(AppContext.get())
        .setListener(purchasesUpdatedListener)
        .enablePendingPurchases()
        .build()

    override fun onClick(v: View?) {

    }

    override fun layoutID(): Int {
        return R.layout.activity_google_pay
    }

    override fun init() {
        id_btn_google_pay.setOnClickListener {

        }
        startConnection()

    }


    fun startConnection() {
        billingClient.startConnection(object : BillingClientStateListener {
            override fun onBillingSetupFinished(billingResult: BillingResult) {
                if (billingResult.responseCode == BillingClient.BillingResponseCode.OK) {
                    // The BillingClient is ready. You can query purchases here.
                    // BillingClient准备好了。你可以在这里查询购买情况。
                    //querySkuDetails()
                    querySkuDetails()
                }
                Log.d(TAG, billingResult.toString())
            }

            override fun onBillingServiceDisconnected() {
                // Try to restart the connection on the next request to
                // 尝试在下一次请求时重新启动连接
                // Google Play by calling the startConnection() method.
                // 谷歌通过调用startConnection()方法来播放。
                startConnection()
                Log.d(TAG, "onBillingServiceDisconnected")
            }
        })
    }

    fun querySkuDetails() {
        val skuList: MutableList<String> = ArrayList()
        skuList.add("premium_upgrade")
        skuList.add("gas")
        val params = SkuDetailsParams.newBuilder()
        params.setSkusList(skuList).setType(SkuType.INAPP)
        billingClient.querySkuDetailsAsync(
            params.build()
        ) { billingResult, skuDetailsList ->
            // Process the result.
            Log.d(TAG, "billingResult ${billingResult.responseCode}")
            Log.d(TAG, "skuDetailsList ${skuDetailsList?.size}")
        }
    }

}