package com.zxhyis.toolss.common.notification

import android.app.ActivityManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.BatteryManager
import android.os.Build
import com.zxhyis.toolss.FileApp
import com.zxhyis.toolss.ad.ComUtils
import com.zxhyis.toolss.ad.PushManager
import com.zxhyis.toolss.ad.bean.PushCfg
import com.zxhyis.toolss.ad.bean.PushCfg.Companion.ID_INSTALL_PACKAGE_PUSH
import com.zxhyis.toolss.ad.bean.PushCfg.Companion.ID_LOW_BATTERY_PUSH
import com.zxhyis.toolss.ad.bean.PushCfg.Companion.ID_UNINSTALL_PACKAGE_PUSH
import com.zxhyis.toolss.common.notification.NotificationHelper.postActionNotification
import com.zxhyis.toolss.logic.LogEx

/**
 * 只监听安装卸载
 */
class PackageBroadcast : BroadcastReceiver() {

    companion object {
        private val TAG = "PackageBroadcast"
        fun Context.newInitBroadcast() {
//            LogEx.logDebug(TAG, "initBroadcast")
            val filter = IntentFilter()
            filter.addAction(Intent.ACTION_PACKAGE_ADDED)
            filter.addAction(Intent.ACTION_PACKAGE_REMOVED)
            filter.addDataScheme("package")
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                registerReceiver(PackageBroadcast(), filter, Context.RECEIVER_EXPORTED)
            } else {
                registerReceiver(PackageBroadcast(), filter)
            }
        }
    }


    override fun onReceive(context: Context, intent: Intent?) {
        LogEx.logDebug(TAG, "onReceive")
        val action = intent?.action ?: 0
        LogEx.logDebug(TAG, "onReceive action=$action")
        when (action) {

            Intent.ACTION_PACKAGE_REMOVED -> {
                FileApp.fContext.postActionNotification(ID_UNINSTALL_PACKAGE_PUSH)
            }

            Intent.ACTION_PACKAGE_ADDED -> {
                FileApp.fContext.postActionNotification(ID_INSTALL_PACKAGE_PUSH)
            }
        }
    }
}