package com.base.pdfreaderallpdfreader.helper

import android.app.Activity
import android.content.Context
import com.base.pdfreaderallpdfreader.BuildConfig
import com.base.pdfreaderallpdfreader.utils.AppPreferences
import com.base.pdfreaderallpdfreader.utils.LogEx
import com.google.android.ump.ConsentDebugSettings
import com.google.android.ump.ConsentForm
import com.google.android.ump.ConsentInformation
import com.google.android.ump.ConsentRequestParameters
import com.google.android.ump.FormError
import com.google.android.ump.UserMessagingPlatform
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch


object UmpUtils {
    var umpCanAd = true
        get() {
            return AppPreferences.getInstance().getBoolean("umpCanAd", field)
        }
        set(value) {
            field = value
            AppPreferences.getInstance().put("umpCanAd", value, true)
        }
    var umpCalled = false
        get() {
            return AppPreferences.getInstance().getBoolean("umpCalled", field)
        }
        set(value) {
            field = value
            AppPreferences.getInstance().put("umpCalled", value, true)
        }

    private fun Context.umpTest(): ConsentDebugSettings {
        val debugSettings = ConsentDebugSettings.Builder(this)
        debugSettings.setDebugGeography(ConsentDebugSettings.DebugGeography.DEBUG_GEOGRAPHY_EEA)
        //通过TEST-DEVICE-HASHED-ID log过滤ConsentDebugSettings 打印测试id,使用测试id来测试
//        debugSettings.addTestDeviceHashedId("TEST-DEVICE-HASHED-ID")
        debugSettings.addTestDeviceHashedId("73FE7C2634104D50A11BE9B902AA0FA6")
        return debugSettings.build()
    }

    var callback: ((canAd: Boolean) -> Unit)? = null


    private val TAG = "UmpUtils"

    fun requestUMP(activity: Activity) {

        val paramsBuild = ConsentRequestParameters.Builder()

        if (BuildConfig.DEBUG) {
            paramsBuild.setConsentDebugSettings(activity.umpTest())
        }

        // 指示用户是否低于同意年龄; true 低于同意年龄
        // 未满同意年龄的用户不会收到 GDPR 消息表单
        paramsBuild.setTagForUnderAgeOfConsent(false)
        val params = paramsBuild.build()

        val consentInformation: ConsentInformation = UserMessagingPlatform.getConsentInformation(activity)

        if (BuildConfig.DEBUG) {
            consentInformation.reset()
        }

        val updateSuccessListener = ConsentInformation.OnConsentInfoUpdateSuccessListener {
            LogEx.logDebug(TAG, "isConsentFormAvailable=${consentInformation.isConsentFormAvailable}")
            if (consentInformation.isConsentFormAvailable) {
                MainScope().launch(Dispatchers.Main) {
                    delay(500)
                    loadAndShowConsentFormIfRequired(activity, consentInformation)
                }
            } else {
                callback?.invoke(true)
                callback = null
            }
        }
        val updateFailureListener = ConsentInformation.OnConsentInfoUpdateFailureListener {
            LogEx.logDebug(TAG, "message=${it.message} errorCode=${it.errorCode}")
            callback?.invoke(true)
            callback = null
        }

        consentInformation.requestConsentInfoUpdate(activity, params, updateSuccessListener, updateFailureListener)
    }

    fun loadAndShowConsentFormIfRequired(activity: Activity, consentInformation: ConsentInformation) {

        UserMessagingPlatform.loadConsentForm(
            activity,
            object : UserMessagingPlatform.OnConsentFormLoadSuccessListener {
                override fun onConsentFormLoadSuccess(consentForm: ConsentForm) {
                    LogEx.logDebug(TAG, "onConsentFormLoadSuccess")
                    consentForm.show(activity) {
                        callback?.invoke(consentInformation.canRequestAds())
                        callback = null
                    }
                }

            },
            object : UserMessagingPlatform.OnConsentFormLoadFailureListener {
                override fun onConsentFormLoadFailure(p0: FormError) {
                    //https://groups.google.com/g/google-admob-ads-sdk/c/x-fyDOfMSqU/m/MeZX3mO4AAAJ
                    LogEx.logDebug(TAG, "onConsentFormLoadFailure ${p0.message} ${p0.errorCode}")
                    callback?.invoke(true)
                    callback = null
                }
            })

//        UserMessagingPlatform.loadAndShowConsentFormIfRequired(activity) { loadAndShowError: FormError? ->
//            LogEx.logDebug(
//                TAG,
//                "loadAndShowConsentFormIfRequired message=${loadAndShowError?.message} errorCode=${loadAndShowError?.errorCode}"
//            )
//            if (loadAndShowError != null) {
//                callback?.invoke(false)
//                callback = null
//            } else {
//                callback?.invoke(consentInformation.canRequestAds())
//                callback = null
//            }
//        }
    }
}