package com.rgt.superr

import android.app.Activity
import android.app.Application
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import com.rgt.superr.business.helper.InstallHelps
import com.rgt.superr.business.helper.NewComUtils
import com.rgt.superr.business.service.StayJobService.Companion.startStayJobService
import com.rgt.superr.utils.ActivityManagerUtils
import com.rgt.superr.utils.AppPreferences
import com.rgt.superr.utils.LogEx
import com.rgt.superr.utils.SolarEngineUtils.initSolarEngine
import com.rgt.superr.utils.SolarEngineUtils.solarkey
import com.facebook.FacebookSdk
import com.google.android.gms.ads.identifier.AdvertisingIdClient
import com.hjq.language.MultiLanguages
import com.hjq.language.OnLanguageListener
import com.reyun.solar.engine.SolarEngineManager
import java.util.Locale
import java.util.UUID
import com.rgt.superr.SpConstObject.appLanguageSp
import com.rgt.superr.SpConstObject.appLanguageCountrySp
import com.rgt.superr.business.ads.AdsMgr
import com.rgt.superr.business.helper.EventUtils
import com.rgt.superr.business.helper.NewComUtils.spConfig
import com.rgt.superr.business.push.fcm.FCMManager
import com.rgt.superr.business.push.notification.MyNotificationManager
import com.rgt.superr.push.receiver.ScreenStatusReceiver
import com.rgt.superr.ui.batteryinfo.BatteryReceiver.Companion.registerBatteryReceiver
import com.rgt.superr.ui.splash.SplashActivity
import com.facebook.appevents.AppEventsLogger
import com.rgt.superr.SpConstObject.appUuid
import com.rgt.superr.SpConstObject.gid
import com.rgt.superr.business.push.receiver.AlarmReceiver.Companion.startAlarm
import com.rgt.superr.business.push.timer.TimerManager.Companion.changeTimer
import com.rgt.superr.business.push.work.RepeatingWorker.Companion.schedulePeriodicWork
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch


class MyApplication : Application() {
    private val TAG = "MyApplication"
    var uuid = ""

    companion object {

        lateinit var appContext: MyApplication

        @JvmField
        var PAUSED_VALUE = 0


        val noLoadingActivities = listOf(
            "full", // 过滤全屏广告
            "adActivity",
            "AdActivity",
            "AppLovinFullscreenActivity",
            SplashActivity::class.java.simpleName,
            // 返回前台时不跳转启动页的 activity
        )
    }

    override fun onCreate() {
        super.onCreate()
        appContext = this


        initUUid()
        initGid()
        initApp()
        initLifeListener()
        initLanguage()

    }

    private fun initLanguage() {

        // 初始化语种切换框架
        MultiLanguages.init(this)

        // 设置语种变化监听器
        MultiLanguages.setOnLanguageListener(object : OnLanguageListener {
            override fun onAppLocaleChange(oldLocale: Locale, newLocale: Locale) {
                appLanguageSp = newLocale.language
                appLanguageCountrySp = newLocale.country
                Log.i("MultiLanguages", "监听到应用切换了语种，旧语种：$oldLocale，新语种：$newLocale")
            }

            override fun onSystemLocaleChange(oldLocale: Locale, newLocale: Locale) {
                Log.i(
                    "MultiLanguages", "监听到系统切换了语种，旧语种：" + oldLocale + "，新语种：" + newLocale +
                            "，是否跟随系统：" + MultiLanguages.isSystemLanguage(this@MyApplication)
                )
            }
        })
    }

    private fun initGid() = MainScope().launch(Dispatchers.IO) {
        try {
            val info: AdvertisingIdClient.Info = AdvertisingIdClient.getAdvertisingIdInfo(applicationContext)
            val advertisingId = info.id
            gid = advertisingId ?: "null"
        } catch (e: Exception) {
            EventUtils.event("gid_exception")
        }

    }

    override fun attachBaseContext(base: Context?) {
        super.attachBaseContext(MultiLanguages.attach(base))
    }

    private fun initUUid() {
        uuid = appUuid
        if (TextUtils.isEmpty(uuid)) {
            uuid = UUID.randomUUID().toString() + System.currentTimeMillis()
            appUuid = uuid
        }
        LogEx.logDebug(TAG, "uuid=${uuid}")
    }

    fun initApp() {

        //初始化广告相关业务
        AdsMgr.init(appContext)

        initPush()

        initAppConfig()

        initFacebook()

        initSolar()

    }

    private fun initSolar() {
        SolarEngineManager.getInstance().preInit(this, solarkey)
        appContext.initSolarEngine(true)
    }

    private fun initFacebook() {
        //初始化facebook sdk
        FacebookSdk.sdkInitialize(applicationContext)
        AppEventsLogger.activateApp(this)
    }

    private fun initPush() {

        kotlin.runCatching {
            startStayJobService()
        }

//        val token = AppPreferences.getInstance().getString("token", "")
        val topic = GlobalConfig.PACKAGE_NAME + "_push"
//        LogEx.logDebug(TAG, "topic=${topic} token=$token")
        FCMManager.initFirebase(this)
        FCMManager.subscribeToTopic(topic)

        changeTimer()
        ScreenStatusReceiver.registerScreenStatusReceiver(this)
//        PackageStatusReceiver.registerPackageStatusReceiver(this)
        registerBatteryReceiver(this)

        //workManager
        schedulePeriodicWork(appContext)

        startAlarm(appContext, 24)
        startAlarm(appContext, 48)
        startAlarm(appContext, 72)

        //开启通知队列
        MyNotificationManager.startNotificationQueue()
    }

    private fun initAppConfig() {

        //初始化sp的配置
        NewComUtils.parseConfigBean(spConfig)

        NewComUtils.requestCfgCallBackMap.put("changeTimer") {
            LogEx.logDebug(TAG, "requestCfgCallBackMap changeTimer")
            changeTimer()
        }

        InstallHelps.init {
            NewComUtils.requestCfg()
        }
    }

    private var lastTimePause = 0L
    private var lastTimeResume = 0L
    private fun isHotLaunch(): Boolean {
        if ((lastTimeResume - lastTimePause) > 5000) {
            return true
        }
        return false
    }

    private fun initLifeListener() {
        registerActivityLifecycleCallbacks(object : ActivityLifecycleCallbacks {
            private var count = 0
            override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
                ActivityManagerUtils.getInstance().addActivity(activity)
            }

            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 {
                        noLoadingActivities.all { !topActivity.localClassName.contains(it, true) }
                    }

                    LogEx.logDebug(
                        TAG,
                        "flag=$flag" + "   activity:" + activity.localClassName + " topActivity=${topActivity?.localClassName}"
                    )

                    if (flag) {
                        topActivity?.startActivity(
                            Intent(
                                topActivity, SplashActivity::class.java
                            ).apply {
                                putExtra("isHotLaunch", true)
                                putExtra("type", -1)
                            })
                    }
                }
                lastTimeResume = 0
            }

            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) {
                ActivityManagerUtils.getInstance().removeActivity(activity)
            }
        })
    }


}