package com.simplecleaner.app.utils

import android.app.Activity
import android.content.Context
import com.simplecleaner.app.BuildConfig
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


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)
    }

class UmpUtils(
    val activity: Activity
) {

    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("E136C135912795B2B1121AFD737A0F0E")
        return debugSettings.build()
    }

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


    private val TAG = "UmpUtils"

    val consentInformation: ConsentInformation = UserMessagingPlatform.getConsentInformation(activity)


    fun requestUMP() {

        val paramsBuild = ConsentRequestParameters.Builder()

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

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


        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)
    }

    private 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
                }
            })
    }
}