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.reward.PAGRewardItem
import com.bytedance.sdk.openadsdk.api.reward.PAGRewardedAd
import com.bytedance.sdk.openadsdk.api.reward.PAGRewardedAdInteractionListener
import com.bytedance.sdk.openadsdk.api.reward.PAGRewardedAdLoadListener
import com.bytedance.sdk.openadsdk.api.reward.PAGRewardedRequest

class PangleRewardMgr {

    private val TAG = "PangleRewardMgr"
    private var mPAGRewardedAd: PAGRewardedAd? = null
    private var showCallBack: AdsShowCallBack? = null

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

                override fun onAdLoaded(ad: PAGRewardedAd?) {
                    LogEx.logDebug(TAG, "onAdLoaded")
                    mPAGRewardedAd = ad
                    callback?.invoke(true)
                }
            })
    }
    fun show(activity: Activity, showCallBack: AdsShowCallBack?) {

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

        this.showCallBack = showCallBack

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


    private fun showReadyAd(ac: Activity) {

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

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

            override fun onAdClicked() {
            }

            override fun onAdDismissed() {
                showCallBack?.close()
            }

            override fun onUserEarnedReward(p0: PAGRewardItem?) {
            }

            override fun onUserEarnedRewardFail(p0: Int, p1: String?) {
            }
        })
        mPAGRewardedAd?.show(ac)
    }

}