package com.base.appzxhy

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.base.appzxhy.business.helper.InstallHelps
import com.base.appzxhy.business.helper.NewComUtils
import com.base.appzxhy.business.service.StayJobService.Companion.startStayJobService
import com.base.appzxhy.utils.ActivityManagerUtils
import com.base.appzxhy.utils.AppPreferences
import com.base.appzxhy.utils.LogEx
import com.base.appzxhy.utils.SolarEngineUtils.initSolarEngine
import com.base.appzxhy.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.base.appzxhy.SpConstObject.appLanguageSp
import com.base.appzxhy.SpConstObject.appLanguageCountrySp
import com.base.appzxhy.business.ads.AdsMgr
import com.base.appzxhy.business.helper.EventUtils
import com.base.appzxhy.business.helper.NewComUtils.spConfig
import com.base.appzxhy.business.push.fcm.FCMManager
import com.base.appzxhy.business.push.notification.MyNotificationManager
import com.base.appzxhy.push.receiver.AlarmReceiver.Companion.startAlarm
import com.base.appzxhy.push.receiver.ScreenStatusReceiver
import com.base.appzxhy.push.timer.TimerManager.Companion.changeTimer
import com.base.appzxhy.push.work.RepeatingWorker.Companion.schedulePeriodicWork
import com.base.appzxhy.ui.batteryinfo.BatteryReceiver.Companion.registerBatteryReceiver
import com.base.appzxhy.ui.splash.SplashActivity
import com.facebook.appevents.AppEventsLogger
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
            AppPreferences.getInstance().put("gid", advertisingId)
        } catch (e: Exception) {
            EventUtils.event("gid_exception")
        }

    }

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

    private fun initUUid() {
        uuid = AppPreferences.getInstance().getString("uuid", "")
        if (TextUtils.isEmpty(uuid)) {
            uuid = UUID.randomUUID().toString() + System.currentTimeMillis()
            AppPreferences.getInstance().put("uuid", uuid)
            LogEx.logDebug(TAG, "uuid=$uuid")
        }
        LogEx.logDebug(TAG, "uuid=${AppPreferences.getInstance().getString("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)

                    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)
            }
        })
    }


}