package com.base.appzxhy

import AlarmUtils.startAlarm
import android.app.Activity
import android.app.Application
import android.content.Context
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import com.base.appzxhy.ads.AdsMgr
import com.base.appzxhy.bean.ConstObject.appLanguageCountrySp
import com.base.appzxhy.bean.ConstObject.appLanguageSp
import com.base.appzxhy.bean.config.AdConfigBean
import com.base.appzxhy.bean.config.ConfigBean
import com.base.appzxhy.bean.config.PopupConfigBean
import com.base.appzxhy.fcm.FCMManager
import com.base.appzxhy.fcm.notification.MyNotificationManager
import com.base.appzxhy.fcm.receiver.BatteryStatusReceiver
import com.base.appzxhy.fcm.receiver.PackageStatusReceiver
import com.base.appzxhy.fcm.receiver.ScreenStatusReceiver
import com.base.appzxhy.fcm.timer.TimerManager.Companion.changeTimer
import com.base.appzxhy.fcm.work.RepeatingWorker.Companion.schedulePeriodicWork
import com.base.appzxhy.helper.EventUtils
import com.base.appzxhy.helper.InstallHelps
import com.base.appzxhy.helper.NewComUtils
import com.base.appzxhy.service.StayJobService.Companion.startJob
import com.base.appzxhy.ui.start.StartActivity
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.bytedance.sdk.openadsdk.api.init.PAGConfig
import com.bytedance.sdk.openadsdk.api.init.PAGSdk
import com.bytedance.sdk.openadsdk.api.init.PAGSdk.PAGInitCallback
import com.bytedance.sdk.shortplay.api.PSSDK
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"
    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() {
        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)
                )
            }
        })
    }

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

    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 initApp() {

        kotlin.runCatching {
            startJob()
        }

        initShortDramaSdk()
        //初始化广告相关业务
        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) {
//                        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 initRemoteConfig() {

        NewComUtils.requestCfg { config ->
            LogEx.logDebug("requestCfg", "config=$config")
            if (config != null) {
                AppPreferences.getInstance().put("config", config)
                initConfig(config)
            } else {
                EventUtils.event("configNull")
            }
        }

    }

    private fun initConfig(config: String) {
        LogEx.logDebug(TAG, "initConfig config=$config")
//        kotlin.runCatching {
        val configBean = Gson().fromJson(config, ConfigBean::class.java)

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

        //配置
        ConfigBean.configBean = configBean

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

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


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

    }

    /**
     * 初始化短剧sdk
     */
    fun initShortDramaSdk() {
        val appId = "8309530"
        val securityKey = "82dc912698c9e4e7cd8176da48906fde"

        val builder = PSSDK.Config.Builder()
        builder.appId(appId)
            .vodAppId("568708")
            .securityKey(securityKey)
            .licenseAssertPath("vod_player.lic")
            .debug(true)
        PSSDK.init(this, builder.build()) { success, errorInfo ->
            LogEx.logDebug(
                TAG, "onInitFinished() called with: success = [$success], errorInfo = [$errorInfo]"
            )
        }

        //合规设置
        PSSDK.setEligibleAudience(true)

        initPangleAdsSDK()
    }

    /**
     * 初始化短剧广告sdk
     */
    private fun initPangleAdsSDK() {
        val builder = PAGConfig.Builder()
        builder.appId("8025677").appIcon(R.drawable.ic_launcher_foreground)
        PAGSdk.init(this, builder.build(), object : PAGInitCallback {
            override fun success() {
                LogEx.logDebug(TAG, "pangle ads sdk init success")
            }

            override fun fail(i: Int, s: String) {
                LogEx.logDebug(TAG, "pangle ads sdk init fail, i=$i, s=$s")
            }
        })
    }

}