package com.all.pdfreader.pdf.reader.ad

import android.app.Activity
import android.util.DisplayMetrics
import android.util.Log
import android.view.View
import android.widget.FrameLayout
import com.all.pdfreader.pdf.reader.util.AnalyticsUtils
import com.google.android.gms.ads.AdListener
import com.google.android.gms.ads.AdRequest
import com.google.android.gms.ads.AdSize
import com.google.android.gms.ads.AdView
import com.google.android.gms.ads.LoadAdError

object BannerManager {

    private data class BannerInfo(val adView: AdView, val container: FrameLayout, var isLoaded: Boolean = false)
    private val bannerMap = mutableMapOf<String, BannerInfo>()

    //因为有多个activity来展示这个banner，所以我们使用act的名称+广告位做为key
    private fun key(placement: AdsInsUtil.AdPlacement, activity: Activity): String {
        return "${placement.name}_${activity::class.java.simpleName}"
    }

    fun loadBanner(
        activity: Activity,
        container: FrameLayout,
        placement: AdsInsUtil.AdPlacement,
        onLoaded: (() -> Unit)? = null
    ) {
        val currentKey = key(placement, activity)//得到当前的key
        val adUnitId = AdsInsUtil.adUnitIdMap[placement] ?: run {
            Log.d(AdsInsUtil.Placement.TAG, "${activity::class.java.simpleName} Banner 未找到广告ID: $placement")
            container.visibility = View.GONE
            return
        }

        Log.d(AdsInsUtil.Placement.TAG, "${activity::class.java.simpleName} Banner $placement 开始加载")
        AnalyticsUtils.logAdEvent(placement, AnalyticsUtils.AdEvent.REQ)

        container.post {
            container.visibility = View.GONE

            val adSize = getAdSize(activity, container)

            // 销毁旧 AdView
            bannerMap[currentKey]?.adView?.destroy()

            val adView = AdView(activity).apply {
                this.adUnitId = adUnitId
                setAdSize(adSize)
                adListener = object : AdListener() {
                    override fun onAdLoaded() {
                        Log.d(AdsInsUtil.Placement.TAG, "${activity::class.java.simpleName} Banner $placement 加载成功")
                        AnalyticsUtils.logAdEvent(placement, AnalyticsUtils.AdEvent.LOADED)

                        val info = bannerMap[currentKey]
                        info?.isLoaded = true

                        // 广告加载成功后显示容器
                        info?.container?.visibility = View.VISIBLE
                        info?.container?.alpha = 0f
                        info?.container?.animate()?.alpha(1f)?.setDuration(300)?.start()

                        onLoaded?.invoke()
                    }

                    override fun onAdFailedToLoad(error: LoadAdError) {
                        Log.d(AdsInsUtil.Placement.TAG, "${activity::class.java.simpleName} Banner $placement 加载失败: ${error.message}")
                        AnalyticsUtils.logAdEvent(
                            placement,
                            AnalyticsUtils.AdEvent.LOAD_FAIL,
                            error.code,
                            error.message
                        )
                        val info = bannerMap[currentKey]
                        info?.isLoaded = false
                        info?.container?.visibility = View.GONE
                    }
                }
            }

            bannerMap[currentKey] = BannerInfo(adView, container)

            container.removeAllViews()
            container.addView(adView)

            adView.loadAd(AdRequest.Builder().build())
        }
    }

    fun onResume(activity: Activity, placement: AdsInsUtil.AdPlacement) {
        Log.d(AdsInsUtil.Placement.TAG, "${activity::class.java.simpleName} Banner $placement 恢复广告")
        val info = bannerMap[key(placement, activity)] ?: return
        info.adView.resume()
        if (info.isLoaded) {
            info.container.visibility = View.VISIBLE
            info.container.alpha = 0f
            info.container.animate().alpha(1f).setDuration(300).start()
        } else {
            info.container.visibility = View.GONE
        }
    }

    fun onPause(activity: Activity, placement: AdsInsUtil.AdPlacement) {
        val info = bannerMap[key(placement, activity)] ?: return
        info.container.visibility = View.GONE//暂停后就隐藏，让回调来显示
        info.adView.pause()
        Log.d(AdsInsUtil.Placement.TAG, "${activity::class.java.simpleName} Banner $placement 暂停广告")
    }

    fun onDestroy(activity: Activity, placement: AdsInsUtil.AdPlacement) {
        val key = key(placement, activity)
        bannerMap[key]?.adView?.destroy()
        bannerMap.remove(key)
        Log.d(AdsInsUtil.Placement.TAG, "${activity::class.java.simpleName} Banner $placement 销毁广告")
    }

    private fun getAdSize(activity: Activity, container: FrameLayout): AdSize {
        val display = activity.windowManager.defaultDisplay
        val outMetrics = DisplayMetrics()
        display.getMetrics(outMetrics)

        var adWidthPixels = container.width.toFloat()
        if (adWidthPixels == 0f) adWidthPixels = outMetrics.widthPixels.toFloat()

        val density = outMetrics.density
        val adWidth = (adWidthPixels / density).toInt()

        return AdSize.getCurrentOrientationAnchoredAdaptiveBannerAdSize(activity, adWidth)
    }
}
