package com.test.basd.smartjunkcleaner

import android.annotation.SuppressLint
import android.app.Activity
import android.app.job.JobInfo
import android.app.job.JobScheduler
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.AppUtils
import com.google.android.gms.ads.MobileAds
import com.google.android.gms.ads.identifier.AdvertisingIdClient
import com.google.firebase.FirebaseApp
import com.test.basd.smartjunkcleaner.activity.splash.NewSplashActivity
import com.test.basd.smartjunkcleaner.display.ActionBroadcast.Companion.initBroadcast
import com.test.basd.smartjunkcleaner.display.fcm.FcmHelper
import com.test.basd.smartjunkcleaner.display.fcm.NotificationJobService
import com.test.basd.smartjunkcleaner.helps.BaseApplication
import com.test.basd.smartjunkcleaner.helps.ComUtils.requestCfg
import com.test.basd.smartjunkcleaner.helps.ConfigHelper
import com.test.basd.smartjunkcleaner.helps.InstallHelps
import com.test.basd.smartjunkcleaner.helps.ads.AdmobUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch

class MyApplication : BaseApplication() {

    companion object {
        var PAUSED_VALUE = 0
    }

    override fun init() {
        initApp()
    }

    fun initApp() {
        if (ConfigHelper.ifAgreePrivacy) {
            MainScope().launch(Dispatchers.IO) {
                try {
                    ConfigHelper.gid = AdvertisingIdClient.getAdvertisingIdInfo(context).id ?: ""
                } catch (_: Exception) {
                }
            }

            initNotificationWork()
            context.initBroadcast()
            MainScope().launch {
                requestCfg()
                InstallHelps.init()
            }
        }
        MobileAds.initialize(this) { initializationStatus ->
            val statusMap =
                initializationStatus.adapterStatusMap
            for (adapterClass in statusMap.keys) {
                val status = statusMap[adapterClass]
                Log.d(
                    "MyApp", String.format(
                        "Adapter name: %s, Description: %s, Latency: %d",
                        adapterClass, status!!.description, status.latency
                    )
                )
            }
        }
        initLifeListener()
    }

    private fun initNotificationWork() {
        FirebaseApp.initializeApp(this)
        FcmHelper.getToken()
        FcmHelper.subscribeToTopic()
    }

    private fun initJob() {
        val jobScheduler = getSystemService(Context.JOB_SCHEDULER_SERVICE) as JobScheduler
        val job = JobInfo.Builder(0, ComponentName(this, NotificationJobService::class.java))
            .setMinimumLatency(0L)
            .setOverrideDeadline(0L)
            .setPersisted(true)
            .build()
        jobScheduler.schedule(job)
    }

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

            override fun onActivityStarted(activity: Activity) {
//                    Log.e("onActivityStarted", "activity=$activity")
                count++
                if (count == 1 && !AppUtils.isAppForeground()) {
                    val topActivity = ActivityUtils.getTopActivity()
                    if (ConfigHelper.noLoadingActivities.all {
                            !topActivity.localClassName.contains(
                                it, true
                            )
                        }) {
                        if (AdmobUtils.isOpenAdLoaded()) {
                            AdmobUtils.showAppOpenAd(activity)
                        } else {
                            topActivity.startActivity(
                                Intent(
                                    topActivity,
                                    NewSplashActivity::class.java
                                ).apply {
                                    putExtra("isHotLaunch", true)
                                })
                        }
                    }
                }
            }

            override fun onActivityResumed(activity: Activity) {
                PAUSED_VALUE = 1
            }

            override fun onActivityPaused(activity: Activity) {
                PAUSED_VALUE = 2
            }

            override fun onActivityStopped(activity: Activity) {
                count--
            }

            override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {}

            override fun onActivityDestroyed(activity: Activity) {}
        })
    }
}