package com.keyborad.theme.trendyborad.environment.ad

import android.annotation.SuppressLint
import android.app.Activity
import android.app.Application
import android.content.Context
import android.os.Bundle
import android.provider.Settings
import android.util.Log
import com.keyborad.theme.trendyborad.environment.ad.async.Async
import com.unity3d.services.ads.adunit.AdUnitActivity
import com.vungle.ads.internal.ui.AdActivity
import com.vungle.ads.internal.ui.view.MRAIDAdWidget

class AdActivityManager {
    private var mCurrentShowAd: Activity? = null//记录当前正在展示的inst广告Activity
    private var mApplicationContext: Context? = null
    private var mAID: String? = null
    private var mListener: InstAdLeaveAndReturnListener? = null
    private var isAdClosed = false//当广告点击了close按钮的时候 设置成true
    private var isAdClicked = false//标记inst是否已是已点击状态

    companion object {
        val instance: AdActivityManager by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
            AdActivityManager()
        }

        fun isAdActivity(activity: Activity): Boolean {
            return (
                    activity is com.tradplus.ads.mgr.interstitial.views.InterNativeActivity
                            || activity is com.vungle.ads.internal.ui.VungleActivity
                            || activity is com.vungle.ads.internal.ui.AdActivity
                            || activity is AdUnitActivity
                    )
        }
    }

    fun getCurrentShowAd(): Activity? {
        return mCurrentShowAd
    }

    fun doDelayClose(delay: Long) {
        Async.scheduleTaskOnUiThread(delay, Runnable { doClose() })
    }

    /**
     *手动关闭当前显示的inst，具体支持哪些平台的inst，在 onActivityResumed 中添加
     */
    fun doClose() {
        mCurrentShowAd?.let { adActivity ->
            Log.d("ocean-brush", "自动关闭 $adActivity")
            when (adActivity) {
                is AdActivity ->{
                    //反射方式关闭
                    try {
                        // 获取 mraidAdWidget 字段
                        val field = AdActivity::class.java.getDeclaredField("mraidAdWidget")
                        field.isAccessible = true
                        val widget = field.get(adActivity) as? MRAIDAdWidget
                        Log.d("ocean-brush", "调用 widget.close()，触发 CloseDelegate -> finish()")
                        widget?.close() ?: run {
                            // 没拿到 widget
                            adActivity.onBackPressed()
                            Log.d("ocean-brush", "liftoff关闭使用onBackPressed()")
                        }
                    } catch (e: Exception) {
                        adActivity.finish()
                        adActivity.moveTaskToBack(true)
                        Log.d("ocean-brush", "liftoff关闭错误，直接finish")
                    }
                }
                else -> {
                    //关闭广告act
                    adActivity.finish()
                    // 强制移除任务栈（适用于某些广告 Activity 仍然存活的情况）
                    adActivity.moveTaskToBack(true)
                }
            }

        }
    }

    fun getContext(): Context? {
        return mApplicationContext
    }

    fun getAID(): String? {
        return mAID
    }

    fun addActivityLifeCallbacks(callbacks: Application.ActivityLifecycleCallbacks?) {
        (mApplicationContext as Application).registerActivityLifecycleCallbacks(callbacks)
    }

    fun removeActivityLifeCallbacks(callbacks: Application.ActivityLifecycleCallbacks?) {
        (mApplicationContext as Application).unregisterActivityLifecycleCallbacks(callbacks)
    }

    //在Application中调用
    @SuppressLint("HardwareIds")
    fun setControl(application: Application) {
        mApplicationContext = application
        application.registerActivityLifecycleCallbacks(object :
            Application.ActivityLifecycleCallbacks {
            override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {

            }

            override fun onActivityStarted(activity: Activity) {

            }

            override fun onActivityResumed(activity: Activity) {
                //此处添加想要控制的广告平台的inst Activity
                try {
                    if (isAdActivity(activity)) {
                        mCurrentShowAd = activity
                        if (isAdClicked) {
                            //点击了admob inst跳转到外部，然后从外部返回app的时候触发
                            mListener?.onReturnAdFromOutside()
                        }
                    }
                } catch (e: Exception) {
                }
            }

            override fun onActivityPaused(activity: Activity) {
                try {
                    if (mCurrentShowAd != null) {
                        if (isAdActivity(activity)) {//onActivityPaused会在很多场景下触发：1.退到桌面 2.去往app外部 3.被dialog挡住 4.广告点击了close按钮销毁的过程中
                            if (!isAdClosed) {//isAdClosed这里就是为了排除"4.广告点击了close按钮销毁的过程中"
                                //需要在不同展示场景中实际测试
                                mListener?.onLeaveAdGoOutside()
                                isAdClicked = true
                            }
                        }
                    }
                } catch (e: Exception) {
                }
            }

            override fun onActivityStopped(activity: Activity) {}
            override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {}
            override fun onActivityDestroyed(activity: Activity) {
                Log.d("ocean-brush", "onActivityDestroyed $activity $mCurrentShowAd")
                if (mCurrentShowAd === activity) {
                    mCurrentShowAd = null
                    isAdClosed = false
                    isAdClicked = false
                    mListener = null
                }
            }
        })
        try {
            mAID = hashCode().toString() + ""
            if (mApplicationContext != null) {
                mAID = Settings.Secure.getString(
                    mApplicationContext?.contentResolver, Settings.Secure.ANDROID_ID
                )
            }
        } catch (e: Exception) {
        }
    }

    fun setAdClose(isClosing: Boolean) {
        isAdClosed = isClosing
    }

    fun setInstAdListener(listener: InstAdLeaveAndReturnListener) {
        mListener = listener
    }

    interface InstAdLeaveAndReturnListener {
        fun onLeaveAdGoOutside()//1.点击ad跳转到外部 2.app切换到后台 3.被dialog遮挡
        fun onReturnAdFromOutside()//从外部返回ad页面, 通常是点击ad跳转到外部后返回ad页面
    }
}