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.business.pangle.PangleEvent.eventPangleAd
import com.base.appzxhy.utils.LogEx
import com.bytedance.sdk.openadsdk.api.open.PAGAppOpenAd
import com.bytedance.sdk.openadsdk.api.open.PAGAppOpenAdInteractionListener
import com.bytedance.sdk.openadsdk.api.open.PAGAppOpenAdLoadListener
import com.bytedance.sdk.openadsdk.api.open.PAGAppOpenRequest

class PangleOpenMgr {

    private val TAG = "PangleOpenMgr"
    private var ttAppOpenAd: PAGAppOpenAd? = null
    private var showCallBack: AdsShowCallBack? = null

    private val slotId: String = GlobalConfig.ID_PANGLE_OPEN

    fun load(callback: ((flag: Boolean) -> Unit)? = null) {
        val request = PAGAppOpenRequest()
        request.timeout = 3000
        PAGAppOpenAd.loadAd(slotId, request, object : PAGAppOpenAdLoadListener {
            override fun onError(code: Int, message: String?) {
                LogEx.logDebug(TAG, "loadAd onError code=$code message=$message")
                callback?.invoke(false)
            }

            override fun onAdLoaded(pagAppOpenAd: PAGAppOpenAd?) {
                LogEx.logDebug(TAG, "onAdLoaded")
                ttAppOpenAd = pagAppOpenAd
                callback?.invoke(true)
            }
        })

    }

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

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

        this.showCallBack = showCallBack

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

    private fun showReadyAd(ac: Activity) {

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

        ttAppOpenAd?.setAdInteractionListener(object : PAGAppOpenAdInteractionListener {
            override fun onAdShowed() {
                showCallBack?.show()

                ttAppOpenAd?.let {
                    eventPangleAd(ac, it)
                }

                ttAppOpenAd = null
                load()
            }

            override fun onAdClicked() {
            }

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

