package com.base.filerecoveryrecyclebin

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import com.base.filerecoveryrecyclebin.activity.SplashActivity
import com.base.filerecoveryrecyclebin.ads.admob.AdmobOpenUtils
import com.base.filerecoveryrecyclebin.ads.max.AdMaxInit.initAdMax
import com.base.filerecoveryrecyclebin.bean.ConstObject.ifAgreePrivacy
import com.base.filerecoveryrecyclebin.fcm.FCMManager
import com.base.filerecoveryrecyclebin.fcm.RecoveryTimerManager
import com.base.filerecoveryrecyclebin.fcm.ScreenStatusReceiver
import com.base.filerecoveryrecyclebin.help.BaseApplication
import com.base.filerecoveryrecyclebin.help.ConfigHelper
import com.base.filerecoveryrecyclebin.utils.ActivityManagerUtils
import com.base.filerecoveryrecyclebin.utils.AppPreferences
import com.base.filerecoveryrecyclebin.utils.InstallHelps
import com.base.filerecoveryrecyclebin.utils.LogEx
import com.base.filerecoveryrecyclebin.utils.NewComUtils
import com.google.android.gms.ads.MobileAds

class MyApplication : BaseApplication() {

    private val TAG = "MyApplication"

    companion object {
        @JvmField
        var PAUSED_VALUE = 0
    }

    override fun init() {
        initApp()
    }

    fun initApp() {
        val topic = ConfigHelper.packageName + "_push"
        FCMManager.initFirebase(this)
        FCMManager.subscribeToTopic(topic)
        LogEx.logDebug(TAG, "topic=${topic}")
        NewComUtils.requestCfg {
            ScreenStatusReceiver.setupScreenStatusListener(this)
            val timerStatus: Int = AppPreferences.getInstance().getString("timerS", "1").toIntOrNull() ?: 1
            if (timerStatus == 0) {
                RecoveryTimerManager.getInstance().stopTaskTimer()
            } else {
                val timerDelay: Int = AppPreferences.getInstance().getString("timerDelay", "1").toIntOrNull() ?: 1
                val timerInterval: Int = AppPreferences.getInstance().getString("timerInterval", "7").toIntOrNull() ?: 7
                if (!RecoveryTimerManager.getInstance().isTaskTimerActive) {
                    RecoveryTimerManager.getInstance().scheduleTask(
                        (timerDelay * 60 * 1000).toLong(),
                        (timerInterval * 60 * 1000).toLong()
                    )
                }
            }
        }
        if (ifAgreePrivacy) {
            InstallHelps.init()

            if (ConfigHelper.admobTrueMaxFlase) {
                MobileAds.initialize(this) { initializationStatus ->
                }
            } else {
                initAdMax()
            }

        }
        initLifeListener()
    }


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

    private fun isHotLaunch(): Boolean {
        if ((lastTimeResume - lastTimePause) > 1000) {
            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) {
                count++
                lastTimeResume = System.currentTimeMillis()
                if (count == 1 && isHotLaunch()) {

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

                    val flag = if (topActivity == null) {
                        true
                    } else {
                        ConfigHelper.noLoadingActivities.all { !topActivity.localClassName.contains(it, true) }
                    }
                    LogEx.logDebug(TAG, "flag=$flag")

                    if (flag) {
                        if (AdmobOpenUtils.isOpenAdLoaded()) {
                            AdmobOpenUtils.showAppOpenAd(activity)
                        } else {
                            topActivity?.startActivity(
                                Intent(
                                    topActivity,
                                    SplashActivity::class.java
                                ).apply {
                                    putExtra("isHotLaunch", true)
                                    putExtra("type", -1)
                                })
                        }
                    }
                }
            }

            override fun onActivityResumed(activity: Activity) {
                PAUSED_VALUE = 1
            }


            override fun onActivityPaused(activity: Activity) {
                PAUSED_VALUE = 2
                lastTimePause = System.currentTimeMillis()

            }

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

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

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


}