package com.base.browserwhite.fcm

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import com.base.browserwhite.bean.ConstObject.ID_INSTALL_APP
import com.base.browserwhite.bean.ConstObject.ID_UNINSTALL_APP
import com.base.browserwhite.fcm.NotificationPushUtil.PUSH_WHERE_UN_INSTALL_BROADCAST
import com.base.browserwhite.fcm.NotificationPushUtil.sendNotificationWhere
import com.base.browserwhite.utils.LogEx


class PackageBroadcastReceiver : BroadcastReceiver() {

    private val TAG = "PackageBroadcastReceiver"
    override fun onReceive(context: Context?, intent: Intent?) {
        LogEx.logDebug(TAG, "onReceive")

        if (intent == null) return

        when (intent.action) {
            Intent.ACTION_PACKAGE_ADDED -> {
                // 获取安装的应用包名
                val packageName = intent.dataString
                // 处理应用安装事件
                LogEx.logDebug(TAG, "PACKAGE_ADDED")

                context?.sendNotificationWhere(ID_INSTALL_APP, PUSH_WHERE_UN_INSTALL_BROADCAST)
            }

            Intent.ACTION_PACKAGE_REMOVED -> {
                // 获取卸载的应用包名
                val packageName = intent.data?.schemeSpecificPart
                // 处理应用卸载事件
                LogEx.logDebug(TAG, "PACKAGE_REMOVED")

                context?.sendNotificationWhere(ID_UNINSTALL_APP, PUSH_WHERE_UN_INSTALL_BROADCAST)
            }
        }
    }

    companion object {
        fun Context.registerPackageBroadcastReceiver(): PackageBroadcastReceiver {
            val packageBroadcastReceiver = PackageBroadcastReceiver()
            val intentFilter = IntentFilter()
            intentFilter.addAction(Intent.ACTION_PACKAGE_ADDED)
            intentFilter.addAction(Intent.ACTION_PACKAGE_INSTALL)
            intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED)
            intentFilter.addDataScheme("package")
            registerReceiver(packageBroadcastReceiver, intentFilter)
            return packageBroadcastReceiver
        }
    }
}
