package com.base.locationsharewhite.ads

import android.app.Activity
import android.content.Context
import android.view.ViewGroup
import com.base.locationsharewhite.ads.admob.AdBannerMgr
import com.base.locationsharewhite.ads.admob.AdInsertMgr
import com.base.locationsharewhite.ads.admob.AdNativeMgr
import com.base.locationsharewhite.ads.admob.AdOpenMgr
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 adInsertMgr by lazy {
        AdInsertMgr()
    }

    private val adNativeMgr by lazy {
        AdNativeMgr()
    }

    private val adBannerMgr by lazy {
        AdBannerMgr()
    }

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

    /**
     * 广告配置项目
     */
    var adsConfigBean: AdsConfigBean? = null
        private set

    /**
     * Init 初始化
     *
     * @param context 这里最好是appContext，因为是耗时操作，等它初始化完毕马上加载开屏和插屏广告
     */
    fun init(context: Context, adsConfigBean: AdsConfigBean) {
        if (adsConfigBean.isInBlackList) return
        AdsMgr.adsConfigBean = adsConfigBean
        MobileAds.initialize(context) {
            val readyAdapter = it.adapterStatusMap.entries.find { entry ->
                entry.value.initializationState == AdapterStatus.State.READY
            }
            isInit = readyAdapter != null
            if (isInit) {
                //成功初始化就提前预加载开屏广告和插页广告
                adOpenMgr.loadAd(context)
                adInsertMgr.loadAd(context)
            }
        }
    }

    /**
     * 展示开屏广告
     *
     * @param activity 当前页面
     * @param showCallBack  展示回调
     */
    fun showOpen(activity: Activity, showCallBack: AdsShowCallBack? = null) {
        adOpenMgr.show(activity, showCallBack)
    }

    /**
     * 展示插屏广告
     *
     * @param activity 当前页面
     * @param showCallBack  展示回调
     */
    fun showInsert(activity: Activity, showCallBack: AdsShowCallBack? = null) {
        if (!isInit || adsConfigBean?.isInBlackList != false) {
            showCallBack?.failed()
            return
        }
        adInsertMgr.show(activity, showCallBack)
    }

    /**
     * 展示原生广告
     *
     * @param parent 需要展示广告的父布局容器
     * @param layout 原生广告布局 ,这里传入的layout要和NativeView里的id一致
     */
    fun showNative(parent: ViewGroup, layout: Int) {
        adNativeMgr.show(parent, layout)
    }

    /**
     * 展示banner广告
     *
     * @param parent 展示广告的父布局容器
     */
    fun showBanner(parent: ViewGroup) {
        if (!isInit || adsConfigBean?.isInBlackList != false) return
        adBannerMgr.show(parent)
    }
}