package com.base.browserwhite

import android.app.Activity
import android.app.Application
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import com.base.browserwhite.fcm.FCMManager
import com.base.browserwhite.fcm.PackageBroadcastReceiver
import com.base.browserwhite.fcm.PackageBroadcastReceiver.Companion.registerPackageBroadcastReceiver
import com.base.browserwhite.fcm.ScreenStatusReceiver
import com.base.browserwhite.help.BlackHelper
import com.base.browserwhite.help.ConfigHelper
import com.base.browserwhite.help.InstallHelps
import com.base.browserwhite.help.WeatherUtils
import com.base.browserwhite.ui.activity.splash.Splash2Activity
import com.base.browserwhite.utils.ActivityManagerUtils
import com.base.browserwhite.utils.AppPreferences
import com.base.browserwhite.utils.LogEx
import com.facebook.FacebookSdk
import com.liulishuo.filedownloader.FileDownloader
import java.util.UUID


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

    companion object {
        lateinit var context: MyApplication

        @JvmField
        var PAUSED_VALUE = 0
    }


    override fun onCreate() {
        super.onCreate()
        context = this
        initUUid()
        initApp()
    }

    private fun initUUid() {
        //使用同一个uuid来测试上报
        //7a6f8e5f-ca67-4149-975b-dacdc6c51aff1723174621132
//        AppPreferences.getInstance().put("uuid", "7a6f8e5f-ca67-4149-975b-dacdc6c51aff1723174621132")
        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")
        }
    }

    fun initApp() {
        FacebookSdk.sdkInitialize(applicationContext)
        val topic = ConfigHelper.packageName + "_push"
        LogEx.logDebug(TAG, "topic=${topic}")
        FCMManager.initFirebase(this)
        FCMManager.subscribeToTopic(topic)
        ScreenStatusReceiver.setupScreenStatusListener(this)
        registerPackageBroadcastReceiver()
        InstallHelps.init()
        BlackHelper.requestBlack()
        initLifeListener()
        initFileDownloader()

        if (!WeatherUtils.hasWeatherDataToday()) {
            WeatherUtils.requestWeatherData()
        }
    }


    private var lastTimePause = 0L
    private var lastTimeResume = 0L
    private fun isHotLaunch(): Boolean {
        if ((lastTimeResume - lastTimePause) > 2000) {
            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) {
                LogEx.logDebug(TAG, "onActivityStarted")

                count++
                lastTimeResume = System.currentTimeMillis()
                if (count == 1 && isHotLaunch()) {

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

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

                    if (activity.localClassName.contains("AppLovinFullscreenActivity")) {
                        flag = false
                    }

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

                    if (flag) {
                        topActivity?.startActivity(
                            Intent(
                                topActivity,
                                Splash2Activity::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)
            }
        })
    }

    private fun initFileDownloader() {

        // 创建 FileDownloader 的配置对象
//        val config = FileDownloader.Config.Builder()
//            .setConnectionComponent(FileDownloadConnection.Impl.create(this).setRetryOnGone(true))
//            .setMinIntervalMillisCallbackProcess(1000) // 设置回调间隔时间
//            .setPath("path/to/your/download/directory", true) // 设置下载文件的存储路径
//            // 其他配置...
//            .build()

        // 初始化 FileDownloader
        FileDownloader.setupOnApplicationOnCreate(this)
    }


}