package com.base.appzxhy.business.pangle

import android.app.Activity
import com.base.appzxhy.GlobalConfig
import com.base.appzxhy.business.ads.AdsShowCallBack
import com.base.appzxhy.utils.LogEx
import com.bytedance.sdk.openadsdk.api.interstitial.PAGInterstitialAd
import com.bytedance.sdk.openadsdk.api.interstitial.PAGInterstitialAdInteractionListener
import com.bytedance.sdk.openadsdk.api.interstitial.PAGInterstitialAdLoadListener
import com.bytedance.sdk.openadsdk.api.interstitial.PAGInterstitialRequest

class PangleInterMgr {

    private val TAG = "PangleInterMgr"
    private var interstitialAd: PAGInterstitialAd? = null
    private var showCallBack: AdsShowCallBack? = null

    fun load(callback: ((flag: Boolean) -> Unit)? = null) {
        PAGInterstitialAd.loadAd(
            GlobalConfig.ID_PANGLE_INTER,
            PAGInterstitialRequest(),
            object : PAGInterstitialAdLoadListener {
                override fun onError(code: Int, message: String?) {
                    LogEx.logDebug(TAG, "loadAd onError code=$code message=$message")
                    callback?.invoke(false)
                }

                override fun onAdLoaded(pagInterstitialAd: PAGInterstitialAd?) {
                    LogEx.logDebug(TAG, "onAdLoaded")
                    interstitialAd = pagInterstitialAd
                    callback?.invoke(true)
                }
            })
    }

    fun show(activity: Activity, showCallBack: AdsShowCallBack?) {

        if (activity.isFinishing || activity.isDestroyed) {
            return
        }

        this.showCallBack = showCallBack

        if (interstitialAd == null) {
            LogEx.logDebug(TAG, "interstitialAd load")
            load {
                if (it) {
                    showReadyAd(activity)
                } else {
                    showCallBack?.adFailed()
                }
            }
        } else {
            LogEx.logDebug(TAG, "interstitialAd ready")
            showReadyAd(activity)
        }
    }

    private fun showReadyAd(ac: Activity) {

        if (ac.isFinishing || ac.isDestroyed) {
            return
        }
        if (interstitialAd == null) {
            showCallBack?.failed()
            return
        }
        LogEx.logDebug(TAG, "interstitialAd show")

        interstitialAd?.setAdInteractionListener(object : PAGInterstitialAdInteractionListener {
            override fun onAdShowed() {
                showCallBack?.show()
                interstitialAd = null
                load()
            }

            override fun onAdClicked() {
            }

            override fun onAdDismissed() {
                showCallBack?.close()
            }
        })
        interstitialAd?.show(ac)
    }

}