package com.base.pdfreaderallpdfreader.helper

import android.app.Activity
import android.app.Application
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import com.base.pdfreaderallpdfreader.BuildConfig
import com.base.pdfreaderallpdfreader.fcm.FCMManager
import com.base.pdfreaderallpdfreader.fcm.ScreenStatusReceiver
import com.base.pdfreaderallpdfreader.helper.WeatherUtils.requestWeatherData
import com.base.pdfreaderallpdfreader.service.StayJobService.Companion.startJob
import com.base.pdfreaderallpdfreader.ui.splash.SplashActivity
import com.base.pdfreaderallpdfreader.utils.ActivityManagerUtils
import com.base.pdfreaderallpdfreader.utils.AppPreferences
import com.base.pdfreaderallpdfreader.utils.LogEx
import com.facebook.FacebookSdk
import com.reyun.solar.engine.OnAttributionListener
import com.reyun.solar.engine.OnInitializationCallback
import com.reyun.solar.engine.SolarEngineConfig
import com.reyun.solar.engine.SolarEngineManager
import com.tom_roush.pdfbox.android.PDFBoxResourceLoader
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 context: MyApplication


        var splashLanguage: String = Locale.getDefault().language
        var mainLanguage: String = Locale.getDefault().language
        var setLanguage: String = Locale.getDefault().language
        var feedbackLanguage: String = Locale.getDefault().language
        var pptLanguage: String = Locale.getDefault().language
        var pdfLanguage: String = Locale.getDefault().language
        var pdfLoadingLanguage: String = Locale.getDefault().language
        var pdfMergeLanguage: String = Locale.getDefault().language
        var pdfSelectLanguage: String = Locale.getDefault().language
        var pdfSplitLanguage: String = Locale.getDefault().language
        var wordLanguage: String = Locale.getDefault().language

        @JvmField
        var PAUSED_VALUE = 0
    }

    override fun onCreate() {
        super.onCreate()
        context = this
        initUUid()
        initApp()
        PDFBoxResourceLoader.init(applicationContext)
        initWeather()
    }

    private fun initWeather() {
        requestWeatherData()
    }

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

    private fun initApp() {
        SolarEngineManager.getInstance().preInit(context, "81a11caa4076cd7c")
        FacebookSdk.sdkInitialize(applicationContext)
//        var topicNumber = System.currentTimeMillis().toFormatMinute()
//        LogEx.logDebug(TAG, "topicNumber=$topicNumber")
//        if (topic_number.isNotEmpty()) {
//            topicNumber = topic_number
//        } else {
//            topic_number = topicNumber
//        }
//        val topic = ConfigHelper.packageName + "_push_$topicNumber"
        val topic = ConfigHelper.packageName + "_push"
        LogEx.logDebug(TAG, "topic=${topic}")
        FCMManager.initFirebase(this)
        FCMManager.subscribeToTopic(topic)
        InstallHelps.init()
        initLifeListener()
        ScreenStatusReceiver.setupScreenStatusListener(this)
        startJob()
    }

     fun initSolarEngine(gdprDeny: Boolean = false) {

        val configBuilder = SolarEngineConfig.Builder()

        if (BuildConfig.DEBUG) {
            configBuilder.logEnabled() //开启本地调试日志
        }
        if (gdprDeny) {
            configBuilder.isGDPRArea = true
            configBuilder.adPersonalizationEnabled = true
            configBuilder.adUserDataEnabled = true
        }
        configBuilder.isCoppaEnabled = true
        configBuilder.setKidsAppEnabled(true)
        configBuilder.fbAppID = ""

        val config = configBuilder.build()

        SolarEngineManager.getInstance().initialize(context, "81a11caa4076cd7c", config,
            OnInitializationCallback { code ->
                if (code == 0) {
                    //初始化成功
                    config.setOnAttributionListener(object : OnAttributionListener {
                        override fun onAttributionSuccess(attribution: JSONObject) {
                            //获取归因结果成功时执行的动作
                            LogEx.logDebug(TAG, "attribution=$attribution")
                            EventHelper.event("install_referrer", attribution.toString())
                        }

                        override fun onAttributionFail(errorCode: Int) {
                            //获取归因结果失败时执行的动作
                            EventHelper.event("SolarEngineManager onAttributionFail errorCode=$errorCode")
                        }
                    })
                } else {
                    //初始化失败，具体失败原因参考下方code码释义
                    EventHelper.event("SolarEngineManager init error code=$code")
                }
            })
    }

    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 {
                        ConfigHelper.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) {
//                LogEx.logDebug(TAG, "onActivityResumed")
                PAUSED_VALUE = 1
            }


            override fun onActivityPaused(activity: Activity) {
//                LogEx.logDebug(TAG, "onActivityPaused")
                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)
            }
        })
    }

}