package com.composition.android.ad.gromore.beizis

import android.content.Context
import com.beizi.ad.BeiZi
import com.beizi.fusion.BeiZiCustomController
import com.beizi.fusion.BeiZis
import com.bytedance.sdk.openadsdk.mediation.bridge.custom.MediationCustomInitLoader
import com.bytedance.sdk.openadsdk.mediation.custom.MediationCustomInitConfig
import com.composition.android.ad.gromore.util.ThreadUtils
import com.composition.android.lib.ad.util.adLogWithFrame
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import kotlinx.coroutines.launch

/**
 * @author: HuBoWen
 * @date: 2023/5/4
 * @description:
 */
class BeiZiInitialize : MediationCustomInitLoader() {

    companion object{
        const val EXTRA_AGREE_AGREEMENT = "extra_agree_agreement"
    }

    override fun initializeADN(context: Context?, customInitConfig: MediationCustomInitConfig?, localExtra: MutableMap<String, Any>?) {
        if(!isInit){
            GlobalScope.launch(Dispatchers.IO) {
                adLogWithFrame("广告", "BenZi广告初始化 外层线程:${Thread.currentThread().name}")
                async (Dispatchers.Main){
                    val agreeAgreement = localExtra?.get(EXTRA_AGREE_AGREEMENT) as? Boolean ?:false
                    adLogWithFrame("广告", "BenZi广告初始化: agree:${agreeAgreement}")
                    val appId = "20826"
                    adLogWithFrame("广告", "BenZi广告真实初始化: appID:${appId},mame:${customInitConfig?.adnName} 线程:${Thread.currentThread().name}")
                    BeiZis.init(context, appId, object : BeiZiCustomController(){
                        override fun isCanUseGaid(): Boolean {
                            return agreeAgreement
                        }

                        override fun isCanUseLocation(): Boolean {
                            return agreeAgreement
                        }

                        override fun isCanUseOaid(): Boolean {
                            return agreeAgreement
                        }

                        override fun isCanUsePhoneState(): Boolean {
                            return agreeAgreement
                        }

                        override fun isCanUseWifiState(): Boolean {
                            return agreeAgreement
                        }
                    })
                }.await()
                adLogWithFrame("广告", "BenZi广告初始化完成:${BeiZis.isIsSyncInit()} 线程:${Thread.currentThread().name}")
                callInitSuccess()
            }
        }
    }

    override fun getNetworkSdkVersion(): String {
        return BeiZis.getSdkVersion()
    }
}