package com.zxhyis.toolss

import android.annotation.SuppressLint
import android.app.Activity
import android.app.Application
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.DeviceUtils
import com.blankj.utilcode.util.NetworkUtils
import com.blankj.utilcode.util.ScreenUtils
import com.google.android.gms.ads.MobileAds
import com.google.android.gms.ads.identifier.AdvertisingIdClient
import com.joinfunchatroom.seetalk.monkey.vitroutils.MainManager
import com.zxhyis.toolss.ad.AdmobUtils
import com.zxhyis.toolss.ad.BlacklistHelper.getBlackList
import com.zxhyis.toolss.ad.ComUtils
import com.zxhyis.toolss.ad.ComUtils.isMainProcess
import com.zxhyis.toolss.ad.ConfigHelper
import com.zxhyis.toolss.ad.EventHelper
import com.zxhyis.toolss.ad.FIRST_LAUNCH_TIME_KEY
import com.zxhyis.toolss.ad.GravitySensorManager
import com.zxhyis.toolss.ad.bean.EventParams
import com.zxhyis.toolss.ad.queryDataStoreBlock
import com.zxhyis.toolss.ad.saveDataStoreBlock
import com.zxhyis.toolss.common.notification.ActionBroadcast.Companion.initBroadcast
import com.zxhyis.toolss.common.notification.NotificationBroadcast
import com.zxhyis.toolss.common.notification.NotificationHelper
import com.zxhyis.toolss.common.notification.PackageBroadcast.Companion.newInitBroadcast
import com.zxhyis.toolss.ui.page.SplashActivity
import com.zxhyis.toolss.ui.receiver.BatteryReceiver
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch

class FileApp : Application() {

    private lateinit var gravitySensorManager: GravitySensorManager
    private var times = 0

    //这些参数都是com.blankj.utilcode.util工具类拿的
    //但是子线程里调用不了  Caused by: java.lang.RuntimeException: Can't create handler inside thread Thread
    var eventParams: EventParams? = null

    companion object {

        lateinit var fContext: FileApp
    }

    /**
     * onCreate 由于保活的存在，重复调用
     */
    override fun onCreate() {
        super.onCreate()
        fContext = this
        initApplication()

//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
//            startForegroundService(Intent(this, AppService::class.java))
//        } else {
//            startService(Intent(this, AppService::class.java))
//        }

    }

    @SuppressLint("UnspecifiedRegisterReceiverFlag")
    fun initApplication() {
        if (isMainProcess(this)) {
            if (ConfigHelper.ifAgreePrivacy) {
                MobileAds.initialize(this)
                MainManager.init(this)
                MainManager.setBh(true)
                ComUtils.requestCfg()
                request()
                MainScope().launch(Dispatchers.IO) {
                    gravitySensorManager = GravitySensorManager(fContext)
                    gravitySensorManager.registerListener()
                    try {
                        ConfigHelper.gid = AdvertisingIdClient.getAdvertisingIdInfo(fContext).id ?: ""
                    } catch (_: Exception) {
                    }
                }
                EventHelper.event("al_start")

                initEvenParams()
                eventParams?.let {
                    NotificationHelper.pushCircleOrderTimber(it)
                }
                registerReceiver(BatteryReceiver(), IntentFilter().apply {
                    addAction("android.intent.action.BATTERY_CHANGED")
                })
                registerReceiver(NotificationBroadcast(), IntentFilter().apply {
                    addAction(NotificationBroadcast.action)
                })

                getBlackList()
                initBroadcast()
                newInitBroadcast()

                //第一次启动时间
                val firstLaunchTime = queryDataStoreBlock(FIRST_LAUNCH_TIME_KEY, 0L)
                if (firstLaunchTime == 0L) {
                    saveDataStoreBlock(FIRST_LAUNCH_TIME_KEY, System.currentTimeMillis())
                }

            }

        }
        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,
                                    SplashActivity::class.java
                                ).apply {
                                    putExtra("isHotLaunch", true)
                                })
                        }
                    }
                }
            }

            override fun onActivityResumed(activity: Activity) {}

            override fun onActivityPaused(activity: Activity) {}

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

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

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


    private fun initEvenParams() {
        eventParams = EventParams(
            ScreenUtils.getScreenHeight(),
            ScreenUtils.getScreenWidth(),
            DeviceUtils.getModel(),
            NetworkUtils.getNetworkType(),
            AppUtils.getAppVersionName(),
            DeviceUtils.getAndroidID()
        )
//        Log.e("initEvenParams", "eventParams=$eventParams")
    }


    private fun request() {
        if (!getSharedPreferences("sp_config_file", Context.MODE_PRIVATE).getBoolean(
                "is_first",
                true
            )
        ) {
            ComUtils.requestCfg()
        }
    }

}