package com.ritoq.quickphone.business.ads

import android.app.Activity
import android.content.Context
import android.view.View
import android.widget.FrameLayout
import androidx.annotation.LayoutRes
import com.ritoq.quickphone.BuildConfig
//import com.applovin.sdk.AppLovinMediationProvider
//import com.applovin.sdk.AppLovinSdk
//import com.applovin.sdk.AppLovinSdkInitializationConfiguration
//import com.base.appzxhy.BuildConfig
import com.ritoq.quickphone.GlobalConfig
import com.ritoq.quickphone.R
import com.ritoq.quickphone.bean.config.AdConfigBean.Companion.adsConfigBean
import com.ritoq.quickphone.bean.config.ConfigBean.Companion.configBean
//import com.base.appzxhy.business.ads.admob.AdBannerMgr
//import com.base.appzxhy.business.ads.admob.AdInterMgr
//import com.base.appzxhy.business.ads.admob.AdNativeMgr
//import com.base.appzxhy.business.ads.admob.AdOpenMgr
//import com.base.appzxhy.business.ads.admob.AdmobEvent
//import com.base.appzxhy.business.ads.applovin.AdMaxEvent
//import com.base.appzxhy.business.ads.applovin.MaxInsertMgr
//import com.base.appzxhy.business.ads.applovin.MaxNativeMgr
//import com.base.appzxhy.business.ads.applovin.MaxOpenMgr
import com.ritoq.quickphone.business.helper.EventUtils
import com.ritoq.quickphone.business.pangle.PangleBannerMgr
import com.ritoq.quickphone.business.pangle.PangleInterMgr
import com.ritoq.quickphone.business.pangle.PangleOpenMgr
import com.ritoq.quickphone.business.pangle.PangleRewardMgr
import com.bytedance.sdk.openadsdk.api.init.PAGConfig
import com.bytedance.sdk.openadsdk.api.init.PAGSdk
import com.bytedance.sdk.openadsdk.api.init.PAGSdk.PAGInitCallback

//import com.google.android.gms.ads.MobileAds
//import com.google.android.gms.ads.initialization.AdapterStatus

/**
 * 广告管理类
 */
object AdsMgr {

//    private val adOpenMgr by lazy {
//        AdOpenMgr()
//    }
//    private val adInterMgr by lazy {
//        AdInterMgr()
//    }
//    private val adNativeMgr by lazy {
//        AdNativeMgr()
//    }
//    private val adBannerMgr by lazy {
//        AdBannerMgr()
//    }

//    private val maxOpenMgr by lazy {
//        MaxOpenMgr()
//    }
//    private val maxInsertMgr by lazy {
//        MaxInsertMgr()
//    }
//    private val maxNativeMgr by lazy {
//        MaxNativeMgr()
//    }

    private val pangleOpenMgr by lazy {
        PangleOpenMgr()
    }

    private val pangleInterMgr by lazy {
        PangleInterMgr()
    }

    private val pangleBannerMgr by lazy {
        PangleBannerMgr()
    }
    private val pangleRewardMgr by lazy {
        PangleRewardMgr()
    }

    /**
     * 是否初始化
     */
//    var isAdmobInit = false
//        private set

    /**
     * 是否初始化
     */
//    var isMaxInit = false
//        private set

    var isAdUtEvent = false

    fun eventAdUt() {
        if (!isAdUtEvent) {
            isAdUtEvent = true
            EventUtils.event("ad_ut_${configBean.ut}")
        }
    }

    /**
     * Init 初始化
     *
     * @param context 这里最好是appContext，因为是耗时操作，等它初始化完毕马上加载开屏和插屏广告
     */
    fun init(context: Context) {
        initPangle(context)
//        if (configBean.isInBlackList) {
//            EventUtils.event("isInBlackList", value = "isInBlackList=${configBean.isInBlackList}")
//            return
//        }
//        initAdmob(context)
//        initMax(context)
    }

//    private fun initAdmob(context: Context) {
//        if (isAdmobInit) return
//        MobileAds.initialize(context) {
//            val readyAdapter = it.adapterStatusMap.entries.find { entry ->
//                entry.value.initializationState == AdapterStatus.State.READY
//            }
//            isAdmobInit = readyAdapter != null
//            EventUtils.event("AdmobInit", "AdmobInit=$isAdmobInit")
////            context.toast("admob init")
//
//            if (adsConfigBean.adSwitch) {
//                admobInitCallBack?.invoke()
//                admobInitCallBack = null
//                adNativeMgr.loadAd(context, AdmobEvent("nativeAd", context::class.java.simpleName))
//                adOpenMgr.loadAd(context, AdmobEvent("openAd", context::class.java.simpleName))
//                adInterMgr.loadAd(context, AdmobEvent("interAd", context::class.java.simpleName))
//            }
//        }
//
//    }

//    private fun initMax(context: Context) = kotlin.runCatching {
//        if (isMaxInit) return@runCatching
//        val executor = Executors.newSingleThreadExecutor()
//
//        executor.execute {
//            val currentGaid = AdvertisingIdClient.getAdvertisingIdInfo(context).id
//            AppPreferences.getInstance().getString("gid", currentGaid)
//
//            val build = AppLovinSdkInitializationConfiguration
//                .builder(GlobalConfig.KEY_MAX, context)
//
//            build.mediationProvider = AppLovinMediationProvider.MAX
//            if (BuildConfig.DEBUG) {
//                build.testDeviceAdvertisingIds = Collections.singletonList(currentGaid)
//            }
//            val initConfig = build.build()
//            runCatching {
//                AppLovinSdk.getInstance(context).initialize(initConfig) {
//                    isMaxInit = true
////                maxOpenMgr.loadAd(context)
//                    if (!adsConfigBean.adSwitch) {
////                        maxInsertMgr.loadAd(context, AdMaxEvent("interAd", context::class.java.simpleName))
//                        context.toast("max init")
//                        maxInitCallBack?.invoke()
//                        maxInitCallBack = null
//                    }
//                }
//            }
//
//        }
//
//    }

//    var admobInitCallBack: (() -> Unit)? = null
//    var maxInitCallBack: (() -> Unit)? = null

    private fun buildNewConfig(context: Context): PAGConfig? {
        return PAGConfig.Builder()
            .appId(GlobalConfig.ID_PANGLE_APPLICATION)
            .appIcon(R.mipmap.logo)
            .debugLog(BuildConfig.DEBUG)
            .supportMultiProcess(false)
            .build()
    }

    fun initPangle(context: Context, next: ((isInit:Boolean) -> Unit)? = null) {
            val pAGInitConfig = buildNewConfig(context)
            PAGSdk.init(context, pAGInitConfig, object : PAGInitCallback {
                override fun success() {

                    val version = PAGSdk.getSDKVersion()
                    val isInitSuccess = PAGSdk.isInitSuccess()
                    next?.invoke(isInitSuccess)
                    //context.toast("pangle init success $version")
                }

                override fun fail(code: Int, msg: String?) {
                    next?.invoke(false)
                    //context.toast("pangle init fail code=$code msg=$msg")
                }
            })
    }


    /**
     * 展示开屏广告
     *
     * @param activity 当前页面
     * @param showCallBack  展示回调
     */
    fun showOpen(
        activity: Activity,
        isUnLimit: Boolean = false,
        showCallBack: AdsShowCallBack? = null,
    ) {
        eventAdUt()

        if (!adsConfigBean.isAdShow) {
            showCallBack?.failed()
            return
        }

//        if (configBean.isInBlackList) {
//            EventUtils.event("isInBlackList", "isInBlackList=${configBean.isInBlackList}")
//            showCallBack?.failed()
//            return
//        }

        val from = activity::class.java.simpleName
//        if (false) {
//            val admobEvent = AdmobEvent("openAd", from).apply { this.isUnLimit = isUnLimit }
//            if (isAdmobInit) {
//                adOpenMgr.show(activity, admobEvent, showCallBack)
//            } else {
//                admobInitCallBack = {
//                }
//                adOpenMgr.show(activity, admobEvent, showCallBack)
//            }
//        } else {
        pangleOpenMgr.show(activity, showCallBack)
//        }

    }

    /**
     * 展示插屏广告
     *
     * @param activity 当前页面
     * @param showCallBack  展示回调
     * @param isUnLimit 是否不受限制 默认false 代表受到限制
     */
    fun showInsert(
        activity: Activity,
        isUnLimit: Boolean = false,
        showCallBack: AdsShowCallBack? = null,
    ) {
        eventAdUt()

        if (!adsConfigBean.isAdShow) {
            showCallBack?.failed()
            return
        }

//        if (configBean.isInBlackList) {
//            EventUtils.event("isInBlackList", configBean.isInBlackList.toString())
//            showCallBack?.failed()
//            return
//        }
//        LogEx.logDebug("showAd", "adSwitch=${adsConfigBean.adSwitch}")
//        val from = activity::class.java.simpleName
//        if (true) {
//            adInterMgr.show(activity, AdmobEvent("interAd", from).apply { this.isUnLimit = isUnLimit }, showCallBack)
//        } else {
//            maxInsertMgr.show(activity, isUnLimit, AdMaxEvent("interAd", from), showCallBack)
//        }
        pangleInterMgr.show(activity, showCallBack)
    }

    /**
     * 展示激励
     */
    fun showReward(
        activity: Activity,
        showCallBack: AdsShowCallBack? = null,
    ) {
        eventAdUt()

        if (!adsConfigBean.isAdShow) {
            showCallBack?.failed()
            return
        }
        pangleRewardMgr.show(activity, showCallBack)
    }

    /**
     * 展示原生广告
     *
     * @param nativeView 需要展示广告的布局容器
     * @param layout 原生广告布局 ,这里传入的layout要和com.example.mydemo.strategy.ads.admob.NativeView里的id一致
     */
    fun showNative(
        nativeView: NativeParentView,
        @LayoutRes layout: Int,
        nativeCallBack: ((Any?) -> Unit)? = null
    ) {
        if (!adsConfigBean.isAdShow) {
            nativeView.visibility = View.GONE
            nativeCallBack?.invoke(null)
            return
        }
        nativeView.visibility = View.VISIBLE
//        if (configBean.isInBlackList) {
//            EventUtils.event("isInBlackList", configBean.isInBlackList.toString())
//            return
//        }

        val showNative = {
            if (true) {
//                adNativeMgr.show(AdmobEvent("nativeAd", "nativeAd"), nativeView, layout, nativeCallBack)
            } else {
//                maxNativeMgr.show(AdMaxEvent("nativeAd", "nativeAd"), nativeView, layout, nativeCallBack)
            }
        }

//        if (isAdmobInit) {
//            showNative.invoke()
//        } else {
//            admobInitCallBack = { showNative.invoke() }
//        }

    }

    /**
     * 展示banner广告
     *
     * @param parent 展示广告的父布局容器
     */
    fun showBanner(
        parent: FrameLayout,
        collapsible: Boolean = true,
        adClose: (() -> Unit)? = null
    ) {
        if (!adsConfigBean.isAdShow) {
            parent.visibility = View.GONE
            return
        }
        parent.visibility = View.VISIBLE
//        if (configBean.isInBlackList) {
//            EventUtils.event("isInBlackList", configBean.isInBlackList.toString())
//            return
//        }
//        if (adsConfigBean.adSwitch) {
//            adBannerMgr.show(parent, collapsible, adClose)
//        }

        pangleBannerMgr.showBanner(parent)
    }
}