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

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

    override fun onCreate() {
        super.onCreate()
        appContext = this
        initUuidIfNeeded()
        initGidAsync()
        initAll()
        registerLifecycle()
        initLanguage()
    }

    // 统一初始化入口
     fun initAll() {
        AdsMgr.init(appContext)
        initPushAndAlarm()
        initAppConfigAndInstall()
        initFacebookAndSolar()
    }

    // UUID初始化
    private fun initUuidIfNeeded() {
        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", "")}")
    }

    // GID异步初始化
    private fun initGidAsync() = MainScope().launch(Dispatchers.IO) {
        try {
            val info = AdvertisingIdClient.getAdvertisingIdInfo(applicationContext)
            SpConstObject.gid = info.id ?: "null"
        } catch (e: Exception) {
            EventUtils.event("gid_exception")
        }
    }

    // 推送、定时、闹钟等初始化
    private fun initPushAndAlarm() {
        kotlin.runCatching { startStayJobService() }
        val topic = GlobalConfig.PACKAGE_NAME + "_push"
        FCMManager.initFirebase(this)
        FCMManager.subscribeToTopic(topic)
        changeTimer()
        ScreenStatusReceiver.registerScreenStatusReceiver(this)
        PackageReceiver.register(this)
        registerBatteryReceiver(this)
        schedulePeriodicWork(appContext)
        listOf(24, 48, 72).forEach { startAlarm(appContext, it) }
        MyNotificationManager.startNotificationQueue()
    }

    // 配置和安装来源初始化
    private fun initAppConfigAndInstall() {
        NewComUtils.parseConfigBean(spConfig)
        NewComUtils.requestCfgCallBackMap["changeTimer"] = {
            LogEx.logDebug(TAG, "requestCfgCallBackMap changeTimer")
            changeTimer()
        }
        InstallHelps.init { NewComUtils.requestCfg() }
    }

    // Facebook和Solar初始化
    private fun initFacebookAndSolar() {
        FacebookSdk.sdkInitialize(applicationContext)
        AppEventsLogger.activateApp(this)
        SolarEngineManager.getInstance().preInit(this, solarkey)
        appContext.initSolarEngine(true)
    }

    // 多语言初始化
    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 registerLifecycle() {
        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 = ActivityManagerUtils.getInstance().topActivity
                    val flag = topActivity == null || 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)
            }
        })
    }

    // 热启动判断
    private fun isHotLaunch(): Boolean = (lastTimeResume - lastTimePause) > 3500

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