package com.vpn.fastestvpnservice.viewmodels

import android.util.Log
import androidx.lifecycle.AndroidViewModel
import com.android.billingclient.api.BillingClient
import com.android.billingclient.api.BillingClientStateListener
import com.android.billingclient.api.BillingResult
import com.android.billingclient.api.Purchase
import com.android.billingclient.api.PurchasesUpdatedListener
import com.android.billingclient.api.SkuDetails
import com.android.billingclient.api.SkuDetailsParams
import com.vpn.fastestvpnservice.application.App
import com.vpn.fastestvpnservice.application.BaseApplication
import com.vpn.fastestvpnservice.beans.ProductFeatures
import com.vpn.fastestvpnservice.beans.UpgradePriceList
import com.vpn.fastestvpnservice.helpers.BasePreferenceHelper

public class BillingViewModel(application: App): AndroidViewModel(application),
    PurchasesUpdatedListener
{


    val tag = "BillingViewModel"
    val prefHelper = BasePreferenceHelper(application.applicationContext)
    private var skuDetailsList: List<SkuDetails>? = null

    private val billingClient: BillingClient by lazy {
        BillingClient.newBuilder(application.applicationContext)
            .setListener(this)
            .enablePendingPurchases()
            .build()
    }

    init {
        Log.d(tag, "init Billing")
        startConnection()
    }

    private fun startConnection() {
        Log.d(tag, "startConnection Billing")

        billingClient.startConnection(object : BillingClientStateListener {

            override fun onBillingSetupFinished(billingResult: BillingResult) {
                if (billingResult.responseCode == BillingClient.BillingResponseCode.OK) {
                    Log.d(tag, "onBillingSetupFinished")
                    Log.d(tag, "BILLING | startConnection | RESULT OK")
                    onLoadProductsClicked()
                } else {
                    Log.d(tag, "BILLING | startConnection | RESULT: ${billingResult.responseCode}")
                }
            }

            override fun onBillingServiceDisconnected() {
                Log.d(tag, "BILLING | onBillingServiceDisconnected | DISCONNECTED")
            }

        })
    }

    private fun onLoadProductsClicked() {
        Log.d(tag, "onLoadProductsClicked Billing")

//        val skuList = listOf("com.fastestvpn.vpn.one.month", "com.fastestvpn.vpn.one.year")
        val skuList: ArrayList<String> = ArrayList<String>()

        val identifierProduct = prefHelper.getFeaturesData()

        identifierProduct.forEachIndexed { index, productFeatures ->
            productFeatures.identifier?.let { skuList.add(it) }
        }

        skuList.forEachIndexed { index, s ->
            Log.d("skulist identidiers", s)
        }

        val skuDetailsListsSubs: MutableList<SkuDetails> = ArrayList<SkuDetails>()
        val params = SkuDetailsParams.newBuilder()
        params.setSkusList(skuList).setType(BillingClient.SkuType.INAPP)

        billingClient.querySkuDetailsAsync(params.build())
        { billingResult, skuDetailsList ->
            if (billingResult.responseCode == BillingClient.BillingResponseCode.OK
                && skuDetailsList != null) {
                for (skuDetails in skuDetailsList) {
                    skuDetailsListsSubs.add(skuDetails)
                }

                params.setType(BillingClient.SkuType.SUBS)
                billingClient.querySkuDetailsAsync(params.build())
                { billingResults, skuDetailsLists ->
                    if (billingResults.responseCode == BillingClient.BillingResponseCode.OK
                        && skuDetailsLists != null) {
                        for (skuDetails in skuDetailsLists) {
                            skuDetailsListsSubs.add(skuDetails)
                        }
//                        initProductList(skuDetailsListsSubs)
                    }
                }
            }
        }
    }

//    private fun initProductList(skuDetailsList: List<SkuDetails>) {
//
//        this.skuDetailsList = skuDetailsList
//        if (this.skuDetailsList?.size!! > 0) {
//
//            var boolValue: Boolean
//            var freePeriod: String
//            var title: String
//            var selectFeatureListSorted = ArrayList<ProductFeatures>()
//
//            for ((index, value) in skuDetailsList.withIndex()){
//                for ((indexed, values) in featuresList.withIndex()){
//
//                    if (value.sku == values.identifier)
//                    {
//                        Log.d("value of sku", "Equal => $index + $indexed")
//                        featuresListSorted.add(featuresList.get(indexed))
//                    }
//                }
//            }
//
//            featuresListSorted.forEachIndexed { index, productFeatures ->
//                Log.d("featuresListSorted", "${productFeatures.title} + ${productFeatures.identifier} + ${productFeatures.price}")
//            }
//
//            for ((index, value) in skuDetailsList.withIndex()){
//
//                Log.d("value of 1", value.title + " ," + value.freeTrialPeriod + "=>" + featuresList.get(index).identifier)
//
//                if (skuDetailsList.size > 1)
//                {
//                    boolValue = index == 1
//                }
//                else{
//                    boolValue = index == 0
//                }
//
//                if (value.freeTrialPeriod == "P3D")
//                {
//                    freePeriod = "Free for 3 days"
//                } else if (value.freeTrialPeriod == "P1W")
//                {
//                    freePeriod = "Free for 7 days"
//                }
//                else
//                {
//                    freePeriod = ""
//                }
//
//
//                selectPriceList.add(
//                    UpgradePriceList(value.title, value.description, value.price, freePeriod,
//                    boolValue, index)
//                )
//            }
//
//            selectPriceList.forEachIndexed { index, upgradePriceList ->
//
//                if (upgradePriceList.isEnabled) {
//                    selectedPosition = index
//                }
//            }
//
//            requireActivity().runOnUiThread(Runnable {
//                if (isVisible) mainActivity.hideLoading()
//
//                upgradeListAdapter.data.clear()
//                if (featuresList.size > 1)
//                {
//                    upgradeListAdapter.setNewData(featuresListSorted.get(1).features)
//                }
//                else if (featuresList.size > 0)
//                {
//                    upgradeListAdapter.setNewData(featuresListSorted.get(0).features)
//                }
//
//                selectPriceListAdapter.data.clear()
//                selectPriceListAdapter.setNewData(selectPriceList)
//                selectPriceListAdapter.notifyDataSetChanged()
//                mDialogBoxes?.hideProgress()
//
//            })
//        }
//    }


    override fun onPurchasesUpdated(p0: BillingResult, p1: MutableList<Purchase>?) {
    }


}