package com.base.scanqrclear

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.scanqrclear.ads.AdsMgr
import com.base.scanqrclear.bean.ConstObject.appLanguageCountrySp
import com.base.scanqrclear.bean.ConstObject.appLanguageSp
import com.base.scanqrclear.bean.config.AdConfigBean
import com.base.scanqrclear.bean.config.ConfigBean
import com.base.scanqrclear.bean.config.PopupConfigBean
import com.base.scanqrclear.fcm.FCMManager
import com.base.scanqrclear.fcm.alarm.AlarmUtils.startAlarm
import com.base.scanqrclear.fcm.timer.TimerManager.Companion.changeTimer
import com.base.scanqrclear.fcm.notification.MyNotificationManager
import com.base.scanqrclear.fcm.receiver.BatteryStatusReceiver
import com.base.scanqrclear.fcm.receiver.PackageStatusReceiver
import com.base.scanqrclear.fcm.receiver.ScreenStatusReceiver
import com.base.scanqrclear.fcm.work.RepeatingWorker.Companion.schedulePeriodicWork
import com.base.scanqrclear.helper.EventUtils
import com.base.scanqrclear.helper.InstallHelps
import com.base.scanqrclear.helper.NewComUtils
import com.base.scanqrclear.luma.AdmobHelps.KEY_INSTALL_TIME
import com.base.scanqrclear.luma.SpUtils
import com.base.scanqrclear.service.StayJobService.Companion.startJob
import com.base.scanqrclear.ui.start.StartActivity
import com.base.scanqrclear.utils.ActivityManagerUtils
import com.base.scanqrclear.utils.AppPreferences
import com.base.scanqrclear.utils.LogEx
import com.base.scanqrclear.utils.SolarEngineUtils.initSolarEngine
import com.base.scanqrclear.utils.SolarEngineUtils.solarkey
import com.base.scanqrclear.utils.WriteLogEx.writeLogFile
import com.facebook.FacebookSdk
import com.google.android.gms.ads.identifier.AdvertisingIdClient
import com.google.gson.Gson
import com.hjq.language.MultiLanguages
import com.hjq.language.OnLanguageListener
import com.reyun.solar.engine.SolarEngineManager
import org.json.JSONObject
import java.util.Locale
import java.util.UUID


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

    companion object {

        lateinit var appContext: MyApplication

        @JvmField
        var PAUSED_VALUE = 0

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


    override fun onCreate() {
        LogEx.logDebug(TAG, "onCreate")
        super.onCreate()
        appContext = this
        initUUid()
        initGid()
        initApp()

        // 初始化语种切换框架
        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)
                )
            }
        })
    }

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

    private fun initGid() {
        Thread {
            kotlin.runCatching {
                val info: AdvertisingIdClient.Info = AdvertisingIdClient.getAdvertisingIdInfo(applicationContext)
                val advertisingId = info.id
                AppPreferences.getInstance().put("gid", advertisingId)
            }
        }.start()
    }

    private fun initApp() {
        if (SpUtils.getInstance().getLong(KEY_INSTALL_TIME) == 0L)
            SpUtils.getInstance().putLong(KEY_INSTALL_TIME, System.currentTimeMillis())
        //前台服务
        kotlin.runCatching {
            startJob()
        }

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

        FacebookSdk.sdkInitialize(applicationContext)
        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)

        initAppConfig()

        SolarEngineManager.getInstance().preInit(this, solarkey)

        initLifeListener()

        ScreenStatusReceiver.registerScreenStatusReceiver(this)
        PackageStatusReceiver.registerPackageStatusReceiver(this)
        BatteryStatusReceiver.registerBatteryStatusReceiver(this)

        //workManager
        schedulePeriodicWork(appContext)

        //闹钟
        startAlarm(appContext, 24)
        startAlarm(appContext, 48)
        startAlarm(appContext, 72)

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

        appContext.initSolarEngine(true)
    }

    private fun initAppConfig() {

        Thread {
            val config = AppPreferences.getInstance().getString("config", "")
            if (config.isNotEmpty()) {
                initConfig(config)
            }

            InstallHelps.init {
                initRemoteConfig()
            }
        }.start()
    }


    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) {
                        LogEx.logDebug(TAG, "onActivityStarted onActivityStarted=$topActivity")
                        topActivity?.startActivity(
                            Intent(
                                topActivity, StartActivity::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 initRemoteConfig() {
        LogEx.logDebug(TAG, "initRemoteConfig")
        NewComUtils.requestCfg { config ->
            if (config != null) {
                AppPreferences.getInstance().put("config", config)
                LogEx.logDebug("requestCfg", "config=$config")
                initConfig(config)
            } else {
                EventUtils.event("configNull")
                writeLogFile("config", "configNull")
            }
        }
    }

    private fun initConfig(config: String) {

        kotlin.runCatching {
            val configBean = Gson().fromJson(config, ConfigBean::class.java)

            writeLogFile("config", config)

            val jsonObject = JSONObject()
            jsonObject.put("ut", configBean.ut)
            EventUtils.event("user_type", ext = jsonObject)
            LogEx.logDebug("initConfig", "ut=${configBean.ut}")

            //配置
            ConfigBean.configBean = configBean

            //广告
            AdConfigBean.adsConfigBean = configBean.adConfigBean
            LogEx.logDebug("initConfig", "adsConfigBean=${AdConfigBean.adsConfigBean.numDisplayLimit}")

            //通知
            PopupConfigBean.popupConfigBean = configBean.popupConfigBean
            LogEx.logDebug("initConfig", "popupConfigBean=${PopupConfigBean.popupConfigBean.timerInterval}")

            //启动定时器
            changeTimer()
        }

    }

}