package com.base.filerecoveryrecyclebin

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import com.base.filerecoveryrecyclebin.activity.splash.Splash2Activity
import com.base.filerecoveryrecyclebin.ads.AdmobMaxHelper
import com.base.filerecoveryrecyclebin.bean.ConstObject.ifAgreePrivacy
import com.base.filerecoveryrecyclebin.fcm.FCMManager
import com.base.filerecoveryrecyclebin.fcm.ScreenStatusReceiver
import com.base.filerecoveryrecyclebin.help.BaseApplication
import com.base.filerecoveryrecyclebin.help.BlackUtils
import com.base.filerecoveryrecyclebin.help.ConfigHelper
import com.base.filerecoveryrecyclebin.help.InstallHelps
import com.base.filerecoveryrecyclebin.help.WeatherUtils
import com.base.filerecoveryrecyclebin.service.StayJobService.Companion.startJob
import com.base.filerecoveryrecyclebin.utils.ActivityManagerUtils
import com.base.filerecoveryrecyclebin.utils.AppPreferences
import com.base.filerecoveryrecyclebin.utils.EventUtils
import com.base.filerecoveryrecyclebin.utils.LogEx
import com.base.filerecoveryrecyclebin.work.schedulePeriodicWork
import com.facebook.FacebookSdk
import com.google.android.gms.ads.identifier.AdvertisingIdClient
import com.reyun.solar.engine.OnAttributionListener
import com.reyun.solar.engine.SolarEngineConfig
import com.reyun.solar.engine.SolarEngineManager
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import org.json.JSONObject
import java.util.UUID

class MyApplication : BaseApplication() {

    private val TAG = "MyApplication"
    var uuid = ""


    companion object {
        var isInterOpenShowing: Boolean = false

        @JvmField
        var PAUSED_VALUE = 0
    }

    override fun init() {
        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(isStartClick: Boolean = false) {

        if (!isStartClick) {
            Log.e("MXL", "initApp: ")
            @Suppress("DEPRECATION")
            FacebookSdk.sdkInitialize(applicationContext)
//            FacebookSdk.setIsDebugEnabled(true)
//            FacebookSdk.addLoggingBehavior(LoggingBehavior.APP_EVENTS)
            val topic = ConfigHelper.packageName + "_push"
            LogEx.logDebug(TAG, "topic=${topic}")
            FCMManager.initFirebase(this)
            FCMManager.subscribeToTopic(topic)
            ScreenStatusReceiver.setupScreenStatusListener(this)
            InstallHelps.init()
            BlackUtils.requestBlack()
            initLifeListener()
            schedulePeriodicWork(this)
            startJob()
            WeatherUtils.requestWeatherData()
        }

        if (ifAgreePrivacy) {
            solarInit()
            MainScope().launch(Dispatchers.Main) {

                val deferred = async(Dispatchers.IO) {
                    try {
                        AdvertisingIdClient.getAdvertisingIdInfo(context).id
                    } catch (_: Exception) {
                        "unknown"
                    }
                }
                val gid = deferred.await() ?: ""
                LogEx.logDebug(TAG, "gid=$gid")
                AppPreferences.getInstance().put("gid", gid)
            }

        }
    }


    private var lastTimePause = 0L
    private var lastTimeResume = 0L

    private fun isHotLaunch(): Boolean {
        if ((lastTimeResume - lastTimePause) > 1000) {
            return true
        }
        return false
    }

    @SuppressLint("UnspecifiedRegisterReceiverFlag")
    private fun initLifeListener() {
        registerActivityLifecycleCallbacks(object : ActivityLifecycleCallbacks {
            private var count = 0
            override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
                LogEx.logDebug(TAG, "activity=$activity")
                ActivityManagerUtils.getInstance().addActivity(activity)
            }

            override fun onActivityStarted(activity: Activity) {
                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")

                    if (flag && !isInterOpenShowing) {
                        if (AdmobMaxHelper.isOpenAdLoaded()) {
//                            var loaded: Boolean = true
//                            AdmobMaxHelper.admobMaxShowOpenAd(activity, {
//                                loaded = it
//                            }, {
//                                val sp = AppPreferences.getInstance().getString("splashShowInter", "0").toInt()
//                                if (sp == 1 && !loaded) {
//                                    AdmobMaxHelper.admobMaxShowInterstitialAd(activity)
//                                }
//                            })
                            topActivity?.startActivity(
                                Intent(
                                    topActivity,
                                    Splash2Activity::class.java
                                ).apply {
                                    putExtra("isHotLaunch", true)
                                    putExtra("type", -1)
                                })
                        } else {
                            topActivity?.startActivity(
                                Intent(
                                    topActivity,
                                    Splash2Activity::class.java
                                ).apply {
                                    putExtra("isHotLaunch", true)
                                    putExtra("type", -1)
                                })
                        }
                    }
                }
            }

            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 solarInit(){
        SolarEngineManager.getInstance().preInit(context, "413882174e882211")
        val config = SolarEngineConfig.Builder()
            //  .logEnabled() //开启本地调试日志
            .build()
        SolarEngineManager.getInstance().initialize(
            context, "413882174e882211", config
        ) { code ->
            if (code == 0) {
                //初始化成功
                config.setOnAttributionListener(object : OnAttributionListener {
                    override fun onAttributionSuccess(attribution: JSONObject) {
                        //获取归因结果成功时执行的动作
                        // Log.e("MXL", "onAttributionSuccess: "+attribution.toString() )
                        EventUtils.event("source_atrribute", ext = attribution)
                    }

                    override fun onAttributionFail(errorCode: Int) {
                        //获取归因结果失败时执行的动作
                        //   Log.e("MXL", "onAttributionFail: "+errorCode )
                    }
                })
            } else {
                //初始化失败，具体失败原因参考下方code码释义
            }
        }
    }
}