package com.test.basd.onecleanmaster

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.os.Process
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.onecleanmaster.activity.splash.NewSplashActivity
import com.test.basd.onecleanmaster.display.ActionBroadcast.Companion.initBroadcast
import com.test.basd.onecleanmaster.display.NotificationService
import com.test.basd.onecleanmaster.display.NotificationUtils
import com.test.basd.onecleanmaster.display.fcm.FcmHelper
import com.test.basd.onecleanmaster.helps.BaseApplication
import com.test.basd.onecleanmaster.helps.ComUtils.requestCfg
import com.test.basd.onecleanmaster.helps.ConfigHelper
import com.test.basd.onecleanmaster.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) {
            Log.e("MXL", "application初始化: ")
            MainScope().launch(Dispatchers.IO) {
                try {
                    ConfigHelper.gid = AdvertisingIdClient.getAdvertisingIdInfo(context).id ?: ""
                } catch (_: Exception) {
                }
            }
            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
                        )
                    )
                }
            }
            initNotificationWork()
            context.initBroadcast()
            MainScope().launch { requestCfg() }
        }
        initLifeListener()
    }

    private fun initNotificationWork() {
        FirebaseApp.initializeApp(this)
        FcmHelper.getToken()
        FcmHelper.subscribeToTopic()
        val isBoolean = NotificationUtils.isNotificationExist(this, 1)
        if (isBoolean) {
            Log.d("MyService", "常驻通知栏存在");
            return
        }
        val intent = Intent(this, NotificationService::class.java)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForegroundService(intent)
        } else {
            startService(intent)
        }
        initBroadcast()
        Log.d("MyService", "startService:" + Process.myPid());
    }

    @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) {}
        })
    }
}