package com.simplecleaner.app.business.ads.admob

import android.app.Activity
import android.content.Context
import com.simplecleaner.app.GlobalConfig
import com.simplecleaner.app.MyApplication
import com.simplecleaner.app.bean.config.AdConfigBean
import com.simplecleaner.app.business.ads.AdCountDownDialog.createUICountdownTimer
import com.simplecleaner.app.business.ads.AdCountDownDialog.showAdCountDownDialog
import com.simplecleaner.app.business.ads.AdEvent
import com.simplecleaner.app.business.ads.AdState
import com.simplecleaner.app.business.ads.AdsShowCallBack
import com.simplecleaner.app.business.ads.AdsType
import com.simplecleaner.app.business.ads.LimitUtils
import com.simplecleaner.app.utils.LogEx
import com.google.android.gms.ads.AdError
import com.google.android.gms.ads.AdRequest
import com.google.android.gms.ads.FullScreenContentCallback
import com.google.android.gms.ads.LoadAdError
import com.google.android.gms.ads.interstitial.InterstitialAd
import com.google.android.gms.ads.interstitial.InterstitialAdLoadCallback
import com.simplecleaner.app.business.ads.admob.AdmobEvent.AdmobOnPaidEventListener

/**
 * 插屏广告加载显示管理类（重构版）
 */
class AdInterMgr {
    // 内部状态管理
    private data class InterAdState(
        var currentAd: InterstitialAd? = null,
        var loading: Boolean = false,
        var adDialog: android.app.Dialog? = null,
        var showCallBack: AdsShowCallBack? = null,
        var loadingCallBack: ((Boolean) -> Unit)? = null,
        var currentAdEvent: AdEvent? = null
    ) {
        fun reset() {
            currentAd = null
            loading = false
            adDialog?.dismiss()
            adDialog = null
            showCallBack = null
            loadingCallBack = null
            currentAdEvent = null
        }
    }

    private val state = InterAdState()

    /**
     * 展示插屏广告
     */
    fun show(
        activity: Activity,
        adEvent: AdEvent,
        showCallBack: AdsShowCallBack? = null
    ) {
        if (activity.isFinishing || activity.isDestroyed) return
        // 关联reqId
        state.currentAdEvent?.let { adEvent.reqId = it.reqId }
        // 限流判断
        if (!adEvent.isUnLimit) {
            if (!LimitUtils.isAdShow(AdsType.INSERT, adEvent)) {
                showCallBack?.failed(2)
                return
            }
            if (LimitUtils.isIntervalInterLimit(adEvent)) {
                showCallBack?.failed(3)
                return
            }
        }
        state.showCallBack = showCallBack
        // 弹窗管理
        state.adDialog?.dismiss()
        state.adDialog = activity.showAdCountDownDialog()
        adEvent.adPrepareShow()
        // 加载或直接展示
        if (state.currentAd == null) {
            if (!state.loading) {
                loadAd(activity, adEvent) { success ->
                    if (success) showReadyAd(activity, adEvent)
                    else state.showCallBack?.adFailed()
                }
            } else {
                state.loadingCallBack = { showReadyAd(activity, adEvent) }
            }
        } else {
            showReadyAd(activity, adEvent)
        }
    }

    /**
     * 展示已准备好的广告
     */
    private fun showReadyAd(activity: Activity, adEvent: AdEvent) {
        val admobEvent = adEvent as? AdmobEvent ?: return
        val ad = state.currentAd
        if (activity.isFinishing || activity.isDestroyed || ad == null) {
            state.showCallBack?.failed()
            state.reset()
            return
        }
        ad.fullScreenContentCallback = object : FullScreenContentCallback() {
            override fun onAdShowedFullScreenContent() {
                state.currentAd = null
                state.showCallBack?.show()
                LimitUtils.addDisplayNum()
                admobEvent.showAd(ad.responseInfo, activity)
            }
            override fun onAdFailedToShowFullScreenContent(adError: AdError) {
                state.showCallBack?.adFailed()
                admobEvent.adShowError(adError)
                state.reset()
            }
            override fun onAdDismissedFullScreenContent() {
                state.showCallBack?.close()
                state.reset()
                // 自动预加载
                loadAd(MyApplication.appContext, AdmobEvent("interAd", "preload"))
            }
            override fun onAdClicked() {
                admobEvent.clickAd(ad.responseInfo)
                LimitUtils.addClickNum()
            }
        }
        if (AdConfigBean.adsConfigBean.showCountdown) {
            createUICountdownTimer(state.adDialog) { ad.show(activity) }
        } else {
            ad.show(activity)
        }
    }

    /**
     * 加载插屏广告
     */
    fun loadAd(
        context: Context,
        adEvent: AdEvent,
        loadCallBack: ((Boolean) -> Unit)? = null
    ) {
        if (!adEvent.isUnLimit && !LimitUtils.isAdShow(AdsType.INSERT, adEvent)) {
            state.showCallBack?.close(4)
            state.reset()
            return
        }
        if (state.loading) return
        state.loading = true
        adEvent.adPulStart()
        state.currentAdEvent = adEvent
        InterstitialAd.load(
            context,
            GlobalConfig.ID_ADMOB_INTER,
            AdRequest.Builder().build(),
            object : InterstitialAdLoadCallback() {
                override fun onAdLoaded(ad: InterstitialAd) {
                    ad.onPaidEventListener = AdmobOnPaidEventListener(ad, adEvent.scope)
                    state.currentAd = ad
                    state.loading = false
                    loadCallBack?.invoke(true)
                    state.loadingCallBack?.invoke(true)
                    state.loadingCallBack = null
                    LimitUtils.addRequestNum()
                    (adEvent as? AdmobEvent)?.pullAd(ad.responseInfo)
                }
                override fun onAdFailedToLoad(error: LoadAdError) {
                    state.currentAd = null
                    state.loading = false
                    loadCallBack?.invoke(false)
                    state.loadingCallBack?.invoke(false)
                    state.loadingCallBack = null
                    (adEvent as? AdmobEvent)?.pullAd(error.responseInfo, error)
                }
            }
        )
    }

    /**
     * 主动释放资源
     */
    fun clear() {
        state.reset()
    }
}
