package autonomyic.polemicalic.congestionic

import android.app.Activity
import android.content.Context
import android.view.View
import android.view.ViewGroup
import androidx.annotation.LayoutRes
import com.applovin.sdk.AppLovinMediationProvider
import com.applovin.sdk.AppLovinSdk
import com.applovin.sdk.AppLovinSdkInitializationConfiguration
import com.base.appzxhy.business.ads.admob.Predestinationic
import com.easy.clean.BuildConfig
import tooic.fatalityic.GlobalConfig
import tooic.fatalityic.Adventurousic
import tooic.fatalityic.corroborateic.indexic.Lurkic.Companion.adsConfigBean
import tooic.fatalityic.corroborateic.indexic.Jewishic.Companion.configBean
import autonomyic.polemicalic.congestionic.complementic.foldic.Indignationic
import autonomyic.polemicalic.congestionic.complementic.foldic.Juvenileic
import autonomyic.polemicalic.congestionic.complementic.foldic.Swayic
import autonomyic.polemicalic.congestionic.complementic.foldic.Epilepticic
import autonomyic.polemicalic.congestionic.distendic.Skirtic
import autonomyic.polemicalic.congestionic.distendic.Synopsisic
import autonomyic.polemicalic.congestionic.distendic.Sleeplessnessic
import autonomyic.polemicalic.congestionic.distendic.Thermometeric
import incredibleic.guffawic.Glowwormic
import tooic.fatalityic.redic.speckledic.hankeringic.Farawayic
import tooic.fatalityic.redic.speckledic.hankeringic.Upholsteryic
import tooic.fatalityic.redic.speckledic.hankeringic.Alongic.toast
import com.google.android.gms.ads.MobileAds
import com.google.android.gms.ads.identifier.AdvertisingIdClient
import com.google.android.gms.ads.initialization.AdapterStatus
import java.util.Collections
import java.util.concurrent.Executors

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

    private val adOpenMgr by lazy {
        Predestinationic()
    }
    private val adInterMgr by lazy {
        Juvenileic()
    }
    private val adNativeMgr by lazy {
        Swayic()
    }
    private val adBannerMgr by lazy {
        Indignationic()
    }

    private val maxOpenMgr by lazy {
        Thermometeric()
    }
    private val maxInsertMgr by lazy {
        Synopsisic()
    }
    private val maxNativeMgr by lazy {
        Sleeplessnessic()
    }

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

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

    var isAdUtEvent = false

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

    /**
     * Init 初始化
     *
     * @param context 这里最好是appContext，因为是耗时操作，等它初始化完毕马上加载开屏和插屏广告
     */
    fun init(context: Context) {

        if (configBean.isInBlackList) {
            Glowwormic.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
            Glowwormic.event("AdmobInit", "AdmobInit=$isAdmobInit")
//            context.toast("admob init")

            if (adsConfigBean.adSwitch) {
                admobInitCallBack?.invoke()
                admobInitCallBack = null
                adNativeMgr.loadAd(Adventurousic.appContext, Epilepticic("nativeAd", "preload"), null)
//                adOpenMgr.loadAd(context, true, Epilepticic("openAd", context::class.java.simpleName))
                adInterMgr.loadAd(context, Epilepticic("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
            Farawayic.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, Skirtic("interAd", context::class.java.simpleName))
                        context.toast("max init")
                        maxInitCallBack?.invoke()
                        maxInitCallBack = null
                    }
                }
            }

        }

    }

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


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

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

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

        val from = activity::class.java.simpleName
        if (adsConfigBean.adSwitch) {
            val admobEvent = Epilepticic("openAd", from)
            admobEvent.isUnLimit = isUnLimit
            if (isAdmobInit) {
                adOpenMgr.show(activity, admobEvent, showCallBack)
            } else {
                admobInitCallBack = {
                }
                adOpenMgr.show(activity, admobEvent, showCallBack)
            }
        } else {
            if (isMaxInit) {
                maxOpenMgr.show(activity, isUnLimit, Skirtic("openAd", from), showCallBack)
            } else {
                maxInitCallBack = {
                    maxOpenMgr.show(activity, isUnLimit, Skirtic("openAd", from), showCallBack)
                }
            }
        }

    }

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

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

        if (configBean.isInBlackList) {
            Glowwormic.event("isInBlackList", configBean.isInBlackList.toString())
            showCallBack?.failed()
            return
        }
        Upholsteryic.logDebug("showAd", "adSwitch=${adsConfigBean.adSwitch}")
        val from = activity::class.java.simpleName
        if (adsConfigBean.adSwitch) {
            adInterMgr.show(activity, isUnLimit, Epilepticic("interAd", from), showCallBack)
        } else {
            maxInsertMgr.show(activity, isUnLimit, Skirtic("interAd", from), showCallBack)
        }
    }

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

        val showNative = {
            if (adsConfigBean.adSwitch) {
                adNativeMgr.show(Epilepticic("nativeAd", "nativeAd"), nativeView, layout, nativeCallBack)
            } else {
                maxNativeMgr.show(Skirtic("nativeAd", "nativeAd"), nativeView, layout, nativeCallBack)
            }
        }

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

    }

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