package com.android.launcher3.settings

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.text.TextUtils
import com.android.launcher3.Launcher
import com.secspace.lib.common.event.RefreshWorkSpaceEvent
import com.secspace.lib.common.function.SwitchInMdm.addDisallowedRunningApp
import com.secspace.lib.common.utils.Prefs
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus

class AppInstallReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        if (intent.action == Intent.ACTION_PACKAGE_ADDED) {
            val packageName = intent.data?.schemeSpecificPart
            if (!TextUtils.isEmpty(packageName)) {
                if (!TextUtils.isEmpty(packageName) && !TextUtils.equals(packageName, context.packageName)) {
                    if (Prefs.isAllowNewApp(context)) {
                        val pkgs = Prefs.getUserShowAppPkgs(context)
                        pkgs.add(packageName)
                        Prefs.setUserShowAppPkgs(context, pkgs)
                        GlobalScope.launch(Dispatchers.IO) {
                            addDisallowedRunningApp(context)
                        }
                        Launcher.forceReload()
                        EventBus.getDefault().post(RefreshWorkSpaceEvent())
                    }
                    EventBus.getDefault().post(RefreshWorkSpaceEvent())
                }
            }
        }
    }
}