package com.base.datarecovery

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import com.base.datarecovery.activity.SplashActivity
import com.base.datarecovery.ads.AdmobMaxHelper
import com.base.datarecovery.bean.ConstObject.ifAgreePrivacy
import com.base.datarecovery.fcm.FCMManager
import com.base.datarecovery.fcm.ScreenStatusReceiver
import com.base.datarecovery.help.BaseApplication
import com.base.datarecovery.help.BlackUtils
import com.base.datarecovery.help.ConfigHelper
import com.base.datarecovery.utils.ActivityManagerUtils
import com.base.datarecovery.utils.AppPreferences
import com.base.datarecovery.utils.InstallHelps
import com.base.datarecovery.utils.LogEx
import com.google.android.gms.ads.identifier.AdvertisingIdClient
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import java.util.UUID

class MyApplication : BaseApplication() {

    private val TAG = "MAX"
    var uuid = ""

    companion object {
        @JvmField
        var PAUSED_VALUE = 0
    }

    override fun init() {
        initUUid()
        initApp()
    }

    private fun initUUid() {
        uuid = AppPreferences.getInstance().getString("uuid", "")
        if (TextUtils.isEmpty(uuid)) {
            uuid = UUID.randomUUID().toString() + System.currentTimeMillis()
            AppPreferences.getInstance().put("uuid", uuid)
        }
    }

    fun initApp(isFirst: Boolean = false) {
        if (!isFirst) {
            val topic = ConfigHelper.packageName + "_push"
            FCMManager.initFirebase(this)
            FCMManager.subscribeToTopic(topic)
            LogEx.logDebug(TAG, "topic=${topic}")
            ScreenStatusReceiver.setupScreenStatusListener(this)
            InstallHelps.init()
            BlackUtils.requestBlack()
            initLifeListener()
        }

        if (ifAgreePrivacy) {

            MainScope().launch(Dispatchers.Main) {

                val deferred = async(Dispatchers.IO) {
                    try {
                        AdvertisingIdClient.getAdvertisingIdInfo(context).id
                    } catch (_: Exception) {
                        "unknown"
                    }
                }
                val gid = deferred.await() ?: ""
                AppPreferences.getInstance().put("gid", gid)
            }
        }

    }


    private var lastTimePause = 0L
    private var lastTimeResume = 0L

    private fun isHotLaunch(): Boolean {
        if ((lastTimeResume - lastTimePause) > 1500) {
            return true
        }
        return false
    }

    @SuppressLint("UnspecifiedRegisterReceiverFlag")
    private fun initLifeListener() {
        registerActivityLifecycleCallbacks(object : ActivityLifecycleCallbacks {
            private var count = 0
            override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {}

            override fun onActivityStarted(activity: Activity) {
                LogEx.logDebug(TAG, "onActivityStarted")
                count++
                lastTimeResume = System.currentTimeMillis()
                if (count == 1 && isHotLaunch()) {

                    val topActivity: Activity? = ActivityManagerUtils.getInstance().topActivity

                    var flag = if (topActivity == null) {
                        true
                    } else {
                        ConfigHelper.noLoadingActivities.all {
                            !topActivity.localClassName.contains(
                                it,
                                true
                            )
                        }
                    }

                    if (activity.localClassName.contains("AppLovinFullscreenActivity")) {
                        flag = false
                    }
                    LogEx.logDebug(TAG, "flag=$flag" + "   activity:" + activity.localClassName)

                    if (flag) {
                        if (AdmobMaxHelper.isOpenAdLoaded()) {
                            LogEx.logDebug(TAG, "show ad")
                            AdmobMaxHelper.admobMaxShowOpenAd(activity, {}, {})
                        } else {
                            LogEx.logDebug(TAG, "jump splash")
                            topActivity?.startActivity(
                                Intent(
                                    topActivity,
                                    SplashActivity::class.java
                                ).apply {
                                    putExtra("isHotLaunch", true)
                                    putExtra("type", -1)
                                })
                        }
                    }
                }
                lastTimeResume = 0
            }

            override fun onActivityResumed(activity: Activity) {
                LogEx.logDebug(TAG, "onActivityResumed")
                PAUSED_VALUE = 1
            }


            override fun onActivityPaused(activity: Activity) {
                PAUSED_VALUE = 2
                LogEx.logDebug(TAG, "onActivityPaused")
                lastTimePause = System.currentTimeMillis()

            }

            override fun onActivityStopped(activity: Activity) {
                count--
            }

            override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {}

            override fun onActivityDestroyed(activity: Activity) {}
        })
    }


}