package com.assimilate.alltrans.common

import android.app.Activity
import android.widget.FrameLayout
import com.assimilate.alltrans.MyApp
import com.lol.apex.ok.google.adlibrary.base.listener.AdLoadListener
import com.lol.apex.ok.google.adlibrary.base.listener.AdShowListener
import com.lol.apex.ok.google.adlibrary.base.listener.LolLoadError
import com.lol.apex.ok.google.adlibrary.base.listener.LolShowError
import com.lol.apex.ok.google.adlibrary.inner.LOLAdsInnerDispatcher
import com.lol.apex.ok.google.adlibrary.inner.base.AdInnerLoadAdapter
import com.lol.apex.ok.google.adlibrary.inner.base.AdInnerShowAdapter
import com.lol.apex.ok.google.adlibrary.inst.LOLAdsInstDispatcher
import com.lol.apex.ok.google.adlibrary.rewarded.LOLAdsRewardedDispatcher

class LolAdWrapper {

    companion object {
        val shared: LolAdWrapper by lazy { LolAdWrapper() }
    }

    interface LoLLoadListener {
        fun loadFailed(error: LolLoadError?) {}
        fun loaded() {}
    }

    interface LolShowListener {
        fun shown() {}
        fun showFailed(error: LolShowError?) {}
        fun closed() {}
    }

    // 有插屏缓存
    fun hasCache(placement: String): Boolean {
        return LOLAdsInstDispatcher.canShow(placement, false)
    }

    // 有激励缓存
    fun hasRewardCache(placement: String): Boolean {
        return LOLAdsRewardedDispatcher.canShow(placement)
    }

    // 无条件加载插屏
    fun loadAd(act: Activity, placement: String, listener: LoLLoadListener? = null) {
        if (act.isFinishing) return
        LOLAdsInstDispatcher.getLoader(act, placement, object : AdLoadListener {
            override fun onAdLoadFailed(error: LolLoadError?) {
                //load广告失败打点
//                val map = mutableMapOf(Pair(AnalysisUtil.PARAM_VALUE, "${error?.msg}"))
//                AnalysisUtil.placeToLogEvent(placement, AnalysisAdState.AD_LOAD_FAILED, map)

                listener?.loadFailed(error)
            }

            override fun onAdLoaded() {
                listener?.loaded()
            }

        }).loadAd()
    }

    //无条件加载激励
    fun loadRewardAd(act: Activity, placement: String, listener: LoLLoadListener? = null) {
        if (act.isFinishing) return
        LOLAdsRewardedDispatcher.getLoader(act, placement, object : AdLoadListener {
            override fun onAdLoadFailed(error: LolLoadError?) {
//                val map = mutableMapOf(Pair(AnalysisUtil.PARAM_VALUE, "${error?.msg}"))
//                AnalysisUtil.placeToLogEvent(placement, AnalysisAdState.AD_LOAD_FAILED, map)
                listener?.loadFailed(error)
            }

            override fun onAdLoaded() {
                listener?.loaded()
            }

        }).loadAd()
    }

    //无缓存加载插屏
    fun loadAdIfNotCached(act: Activity, placement: String, listener: LoLLoadListener? = null) {
        if (act.isFinishing || hasCache(placement)) return

        loadAd(act, placement, listener)
    }

    //有缓存（包含全局）展示
    fun showAdIfCached(act: Activity, placement: String, listener: LolShowListener? = null) {
//        if (act.isFinishing || !hasCache(placement)) {
////            val map = mutableMapOf(Pair(AnalysisUtil.PARAM_VALUE, "No cache for ads"))
////            AnalysisUtil.placeToLogEvent(placement, AnalysisAdState.AD_SHOW_FAILED, map)
//            listener?.showFailed(LolShowError("No cache for ads"))
//        } else {
//            showAd(act, placement, listener)
//        }

        //判断当前广告位是否可以show，不能show则判断补位广告是否可以show。
        if (act.isFinishing || !hasCache(placement)) {
            if (hasCache(MyApp.Config.backup_int_auto)) {
                showAd(act, MyApp.Config.backup_int_auto, listener)
            } else {
//                    val map = mutableMapOf(Pair(AnalysisUtil.PARAM_VALUE, "No cache for ads"))
//                    AnalysisUtil.placeToLogEvent(placement, AnalysisAdState.AD_SHOW_FAILED, map)
                listener?.showFailed(LolShowError("No cache for ads"))
            }
        } else {
            showAd(act, placement, listener)
        }


    }

    // 带时间带缓存展示
    fun showAdTiming(act: Activity, placement: String, listener: LolShowListener? = null) {
        //当前时间减去旧时间,才展示广告（满足间隔时间才show广告）
        if (System.currentTimeMillis() - MyApp.app.lastAdDisplayTime.get() >= AppStore(MyApp.app).showAdIntervalTime) {
            //判断当前广告位是否可以show，不能show则判断补位广告是否可以show。
            if (act.isFinishing || !hasCache(placement)) {
                if (hasCache(MyApp.Config.backup_int_auto)) {
                    showAd(act, MyApp.Config.backup_int_auto, listener)
                } else {
//                    val map = mutableMapOf(Pair(AnalysisUtil.PARAM_VALUE, "No cache for ads"))
//                    AnalysisUtil.placeToLogEvent(placement, AnalysisAdState.AD_SHOW_FAILED, map)
                    listener?.showFailed(LolShowError("No cache for ads"))
                }
            } else {
                showAd(act, placement, listener)
            }
        }
    }

    // 无条件展示
    private fun showAd(act: Activity, placement: String, listener: LolShowListener? = null) {
        if (act.isFinishing) return
        LOLAdsInstDispatcher.getShower(act, placement, object : AdShowListener {

            override fun onAdClicked() {
                MyApp.app.isAdShowing.set(true)
            }

            override fun onAdClosed() {
                MyApp.app.isAdShowing.set(false)
                listener?.closed()
            }

            override fun onAdRewarded() {}
            override fun onAdShowFailed(error: LolShowError?) {
                MyApp.app.isAdShowing.set(false)
                //广告show失败打点
//                val map = mutableMapOf(Pair(AnalysisUtil.PARAM_VALUE, "${error?.msg}"))
//                AnalysisUtil.placeToLogEvent(placement, AnalysisAdState.AD_SHOW_FAILED, map)
                listener?.showFailed(error)

            }

            override fun onAdShown() {
                MyApp.app.isAdShowing.set(true)
                listener?.shown()
                // AnalysisUtil.placeToLogEvent(placement, AnalysisAdState.AD_SHOWN)
                if (placement != MyApp.Config.start_cold_int_auto) {
                    MyApp.app.lastAdDisplayTime.set(System.currentTimeMillis())
                }
            }

            override fun onAfterClickClosed() {}

            override fun onDelayClosed() {}

        }).showAd()
    }

    //加载展示原生
    fun loadAdShowNativeAd(
        context: Activity, nativeId: String, frameAd: FrameLayout, admobLayout: Int, maxLayout: Int
    ) {
        val inner = LOLAdsInnerDispatcher(context, object : AdInnerLoadAdapter() {
            //设置广告位
            override fun getPlace(): String {
                return nativeId
            }

            //设置admob的native广告布局
            override fun getAdmobLayoutResId(): Int {
                return admobLayout
            }

            override fun getMaxLayoutResId(): Int {
                return maxLayout
            }
        })

        inner.addAdLoadListener(object : AdLoadListener {

            override fun onAdLoadFailed(error: LolLoadError?) {

            }

            override fun onAdLoaded() {

            }
        })

        //广告展示监听回调
        inner.addAdShowListener(object : AdShowListener {
            override fun onAdClicked() {

            }

            override fun onAdRewarded() {

            }

            override fun onAdShowFailed(error: LolShowError?) {
            }

            override fun onAdShown() {}
            override fun onAdClosed() {}
            override fun onAfterClickClosed() {}
            override fun onDelayClosed() {}
        })

        inner.loadAd2Show(object : AdInnerShowAdapter() {
            override fun getAdContainer(): FrameLayout {
                return frameAd
            }
        })
    }


}

