package com.zxhy.fastfilemanagerpro.kokoads

import android.app.Activity
import android.content.Context
import com.google.android.ump.ConsentDebugSettings
import com.google.android.ump.ConsentInformation
import com.google.android.ump.ConsentRequestParameters
import com.google.android.ump.FormError
import com.google.android.ump.UserMessagingPlatform

/**
 * 广告同意管理
 */
class GoogleMobileAdsConsentManager private constructor(context: Context) {

    //同意信息
    private val consentInformation: ConsentInformation =
        UserMessagingPlatform.getConsentInformation(context)

    //是否可请求广告
    val canRequestAds: Boolean
        get() = consentInformation.canRequestAds()

    /**
     * UMP SDK 获取同意信息可用于展示
     */
    fun gatherConsent(
        activity: Activity,
        consentGatheringComplete: (formError: FormError?) -> Unit
    ) {
        val debugSettings =
            ConsentDebugSettings.Builder(activity)
                .addTestDeviceHashedId("TEST-DEVICE-HASHED-ID")
                .build()

        val params =
            ConsentRequestParameters.Builder().setConsentDebugSettings(debugSettings).build()


        consentInformation.requestConsentInfoUpdate(activity, params,
            {//同意信息上传成功回调
                UserMessagingPlatform.loadAndShowConsentFormIfRequired(activity) { formError ->
                    consentGatheringComplete.invoke(formError)
                }
            },
            //同意信息上传失败回调
            { requestConsentError ->
                consentGatheringComplete.invoke(requestConsentError)
            }
        )

    }


    companion object {
        @Volatile
        private var instance: GoogleMobileAdsConsentManager? = null

        fun getInstance(context: Context) = instance ?: synchronized(this) {
            instance ?: GoogleMobileAdsConsentManager(context).also { instance = it }
        }
    }
}