package tooic.fatalityic

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 incredibleic.guffawic.Glowwormic
import incredibleic.guffawic.InstallHelps
import incredibleic.guffawic.Equalizeic
import cottonwoodic.proprietoric.gutic.Wasic.Companion.startStayJobService
import tooic.fatalityic.redic.speckledic.hankeringic.Regionalic
import tooic.fatalityic.redic.speckledic.hankeringic.Farawayic
import tooic.fatalityic.redic.speckledic.hankeringic.Upholsteryic
import tooic.fatalityic.redic.speckledic.hankeringic.Shelveic.initSolarEngine
import tooic.fatalityic.redic.speckledic.hankeringic.Shelveic.solarkey
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
import tooic.fatalityic.Runawayic.appLanguageSp
import tooic.fatalityic.Runawayic.appLanguageCountrySp
import tooic.fatalityic.corroborateic.indexic.Lurkic
import tooic.fatalityic.corroborateic.indexic.Jewishic
import tooic.fatalityic.corroborateic.indexic.Friendlinessic
import autonomyic.polemicalic.congestionic.Unwindic
import incredibleic.guffawic.Equalizeic.spConfig
import hymnalic.underhandedic.rutic.Invigoratingic
import upkeepic.Explanationic
import harrowingic.entitledic.Calamityic.Companion.startAlarm
import harrowingic.entitledic.Dissociateic
import groovyic.runic.volleyballic.Cladic.Companion.changeTimer
import pollutionic.postmarkic.gentlenessic.Sullenlyic.Companion.schedulePeriodicWork
import mudslingingic.hackic.thanksic.Tintic.Companion.registerBatteryReceiver
import astonishic.chandelieric.Jostleic
import com.facebook.appevents.AppEventsLogger


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

    companion object {

        lateinit var appContext: Adventurousic

        @JvmField
        var PAUSED_VALUE = 0


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

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


        initUUid()
        initGid()
        initApp()
        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@Adventurousic)
                )
            }
        })
    }

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

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

    private fun initUUid() {
        uuid = Farawayic.getInstance().getString("uuid", "")
        if (TextUtils.isEmpty(uuid)) {
            uuid = UUID.randomUUID().toString() + System.currentTimeMillis()
            Farawayic.getInstance().put("uuid", uuid)
            Upholsteryic.logDebug(TAG, "uuid=$uuid")
        }
        Upholsteryic.logDebug(TAG, "uuid=${Farawayic.getInstance().getString("uuid", "")}")
    }

    fun initApp() {

        kotlin.runCatching {
            startStayJobService()
        }

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

        //初始化facebook sdk
        FacebookSdk.sdkInitialize(applicationContext)
        AppEventsLogger.activateApp(this)


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

        initAppConfig()

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

        initLifeListener()

        Dissociateic.registerScreenStatusReceiver(this)
//        PackageStatusReceiver.registerPackageStatusReceiver(this)
        registerBatteryReceiver(this)

        //workManager
        schedulePeriodicWork(appContext)

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

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

        appContext.initSolarEngine(true)

    }

    private fun initAppConfig() {
        Thread {
            initConfig()

            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?) {
                Regionalic.getInstance().addActivity(activity)
            }

            override fun onActivityStarted(activity: Activity) {
                count++
                lastTimeResume = System.currentTimeMillis()
                if (count == 1 && isHotLaunch()) {

                    val topActivity: Activity? = Regionalic.getInstance().topActivity

                    val flag = if (topActivity == null) {
                        true
                    } else {
                        noLoadingActivities.all { !topActivity.localClassName.contains(it, true) }
                    }

                    Upholsteryic.logDebug(TAG, "flag=$flag" + "   activity:" + activity.localClassName)

                    if (flag) {
                        topActivity?.startActivity(
                            Intent(
                                topActivity, Jostleic::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) {
                Regionalic.getInstance().removeActivity(activity)
            }
        })
    }

    private fun initRemoteConfig() {

        Equalizeic.requestCfg { config ->
            Upholsteryic.logDebug("requestCfg", "config=$config")
            if (config != null) {
                Farawayic.getInstance().put("config", config)
                initConfig(config)
            } else {
                Glowwormic.event("configNull")
            }
        }

    }

    private fun initConfig(config: String = spConfig) {
        if (config.isEmpty()) return

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

        val jsonObject = JSONObject()
        jsonObject.put("ut", configBean.ut)
        Glowwormic.event("user_type", ext = jsonObject)

        //配置
        Jewishic.configBean = configBean

        //广告
        Lurkic.adsConfigBean = configBean.adConfigBean
        Upholsteryic.logDebug("initConfig", "adsConfigBean=${configBean.adConfigBean.functionInShowAd}")

        //通知配置
        Friendlinessic.popupConfigBean = configBean.popupConfigBean
        Upholsteryic.logDebug("initConfig", "popupConfigBean=${configBean.popupConfigBean.popupCount}")


        //启动定时器
        changeTimer()
//        }

    }


}