package com.base.datarecovery

import android.annotation.SuppressLint
import android.app.Activity
import android.app.AlarmManager
import android.app.PendingIntent
import android.app.job.JobService
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import androidx.work.Constraints
import androidx.work.ExistingPeriodicWorkPolicy
import androidx.work.NetworkType
import androidx.work.PeriodicWorkRequestBuilder
import androidx.work.WorkManager
import com.base.datarecovery.activity.newfunction.WeatherUtils
import com.base.datarecovery.activity.splash.Splash2Activity
import com.base.datarecovery.ads.AdmobMaxHelper
import com.base.datarecovery.bean.ConstObject.ifAgreePrivacy
import com.base.datarecovery.fcm.FCMManager
import com.base.datarecovery.fcm.ScreenStatusReceiver
import com.base.datarecovery.fcm.work.AlterReceiver
import com.base.datarecovery.fcm.work.AlterReceiver2
import com.base.datarecovery.fcm.work.WorkHelp
import com.base.datarecovery.help.BaseApplication
import com.base.datarecovery.help.BlackUtils
import com.base.datarecovery.help.ConfigHelper
import com.base.datarecovery.service.StayJobService.Companion.startJob
import com.base.datarecovery.utils.ActivityManagerUtils
import com.base.datarecovery.utils.AppPreferences
import com.base.datarecovery.utils.EventUtils
import com.base.datarecovery.utils.InstallHelps
import com.base.datarecovery.utils.LogEx
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.Calendar
import java.util.UUID
import java.util.concurrent.TimeUnit

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

        startJob()
        initLifeListener()
        solarInit()
        if (ifAgreePrivacy) {
            initApp()
        }
        startWorkManager()
        startAlarm()
        start48Alarm()
        start72Alarm()
    }

    fun initApp() {
        uuid = AppPreferences.getInstance().getString("uuid", "")
        if (TextUtils.isEmpty(uuid)) {
            uuid = UUID.randomUUID().toString() + System.currentTimeMillis()
            AppPreferences.getInstance().put("uuid", uuid)
        }
        FacebookSdk.sdkInitialize(applicationContext)
//            FacebookSdk.setIsDebugEnabled(true)
//            FacebookSdk.addLoggingBehavior(LoggingBehavior.APP_EVENTS)
        val topic = ConfigHelper.packageName + "_push"
        FCMManager.initFirebase(this)
        FCMManager.subscribeToTopic(topic)
        LogEx.logDebug(TAG, "topic=${topic}")
        ScreenStatusReceiver.setupScreenStatusListener(this)
        InstallHelps.init()
        BlackUtils.requestBlack()
        initLifeListener()
        WeatherUtils.requestWeatherData()
        //  startJob()


        if (ifAgreePrivacy) {

            MainScope().launch(Dispatchers.Main) {

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

    }

    fun startWorkManager() {
        // WorkManager.getInstance(this).cancelAllWorkByTag("ScannerWorker")
        WorkManager.getInstance(this).enqueueUniquePeriodicWork(
            "ScannerWorker",
            ExistingPeriodicWorkPolicy.KEEP,
            PeriodicWorkRequestBuilder<WorkHelp>(15, TimeUnit.MINUTES)
                .setConstraints(
                    Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build()
                )
                .addTag("ScannerWorker")
                .build()
        )
    }


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

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

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

            override fun onActivityStarted(activity: Activity) {
//                LogEx.logDebug(TAG, "onActivityStarted")
                count++
                lastTimeResume = System.currentTimeMillis()
                if (count == 1 && isHotLaunch()) {

                    val topActivity: Activity? = ActivityManagerUtils.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 && !isInterOpenShowing) {
                        if (AdmobMaxHelper.isOpenAdLoaded()) {

                            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)
                                })
                        }
                    }
                }
                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.removeActivity(activity)
            }
        })
    }

    private fun solarInit() {
        SolarEngineManager.getInstance().preInit(context, "f6b7345fd1edd658")
        val config = SolarEngineConfig.Builder()
            //  .logEnabled() //开启本地调试日志
            .build()
        SolarEngineManager.getInstance().initialize(
            context, "f6b7345fd1edd658", 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码释义
            }
        }

    }

    fun startAlarm() {

        val alarmManager = getSystemService(JobService.ALARM_SERVICE) as AlarmManager
        val pendingIntent = PendingIntent.getBroadcast(
            this, 1,
            Intent(this, AlterReceiver::class.java),
            PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
        )
        val calendar = Calendar.getInstance()
        calendar.set(Calendar.HOUR_OF_DAY, 6)
        calendar.set(Calendar.MINUTE, 0)
        calendar.set(Calendar.SECOND, 0)
        alarmManager.setRepeating(
            AlarmManager.RTC_WAKEUP,
            calendar.timeInMillis,
            1800000,
            pendingIntent
        )
    }

    fun start48Alarm() {
        val alarmManager = getSystemService(JobService.ALARM_SERVICE) as AlarmManager
        val pendingIntent = PendingIntent.getBroadcast(
            this, 2,
            Intent(this, AlterReceiver2::class.java),
            PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
        )
        val calendar = Calendar.getInstance()
        calendar.set(Calendar.HOUR_OF_DAY, 6)
        calendar.set(Calendar.MINUTE, 0)
        calendar.set(Calendar.SECOND, 0)
        alarmManager.setRepeating(
            AlarmManager.RTC_WAKEUP,
            calendar.timeInMillis,
            1800000 * 2 * 48,
            pendingIntent
        )
    }

    fun start72Alarm() {
        val alarmManager = getSystemService(JobService.ALARM_SERVICE) as AlarmManager
        val pendingIntent = PendingIntent.getBroadcast(
            this, 3,
            Intent(this, AlterReceiver2::class.java),
            PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
        )
        val calendar = Calendar.getInstance()
        calendar.set(Calendar.HOUR_OF_DAY, 6)
        calendar.set(Calendar.MINUTE, 0)
        calendar.set(Calendar.SECOND, 0)
        alarmManager.setRepeating(
            AlarmManager.RTC_WAKEUP,
            calendar.timeInMillis,
            1800000 * 2 * 72,
            pendingIntent
        )
    }

}