package com.simplecleaner.app

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.simplecleaner.app.business.helper.InstallHelps
import com.simplecleaner.app.business.helper.NewComUtils
import com.simplecleaner.app.business.service.StayJobService.Companion.startStayJobService
import com.simplecleaner.app.utils.ActivityManagerUtils
import com.simplecleaner.app.utils.AppPreferences
import com.simplecleaner.app.utils.LogEx
import com.simplecleaner.app.utils.SolarEngineUtils.initSolarEngine
import com.simplecleaner.app.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.simplecleaner.app.SpConstObject.appLanguageSp
import com.simplecleaner.app.SpConstObject.appLanguageCountrySp
import com.simplecleaner.app.business.ads.AdsMgr
import com.simplecleaner.app.business.helper.EventUtils
import com.simplecleaner.app.business.helper.NewComUtils.spConfig
import com.simplecleaner.app.business.push.fcm.FCMManager
import com.simplecleaner.app.business.push.notification.MyNotificationManager
import com.simplecleaner.app.push.receiver.ScreenStatusReceiver
import com.simplecleaner.app.ui.batteryinfo.BatteryReceiver.Companion.registerBatteryReceiver
import com.simplecleaner.app.ui.splash.SplashActivity
import com.facebook.appevents.AppEventsLogger
import com.simplecleaner.app.SpConstObject.appUuid
import com.simplecleaner.app.business.push.receiver.AlarmReceiver.Companion.startAlarm
import com.simplecleaner.app.business.push.receiver.PackageReceiver
import com.simplecleaner.app.business.push.timer.TimerManager.Companion.changeTimer
import com.simplecleaner.app.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 ?: "null"
            SpConstObject.gid = advertisingId
        } 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")
        }
        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 topic = GlobalConfig.PACKAGE_NAME + "_push"
        FCMManager.initFirebase(this)
        FCMManager.subscribeToTopic(topic)

        changeTimer()
        ScreenStatusReceiver.registerScreenStatusReceiver(this)
        PackageReceiver.register(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) > 3500) {
            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)
            }
        })
    }


}