package com.secspace.lib.common.function

import android.content.Context
import android.content.Intent
import android.content.pm.ApplicationInfo
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.content.pm.ResolveInfo
import android.util.Log
import com.secspace.lib.common.arouter.libwork.IWorkApi
import com.secspace.lib.common.env.Packages.PkgSecSpace
import com.secspace.lib.common.utils.DisableCompat
import com.secspace.lib.common.utils.DpmHelper
import com.secspace.lib.common.utils.MdmUtils
import com.secspace.lib.common.utils.Package.ComponentNames.COMPONENT_UPDATE_SYSTEM
import com.secspace.lib.common.utils.Package.ComponentNames.EnterprisePrivacySettingsActivity
import com.secspace.lib.common.utils.Prefs
import com.secspace.mdmengine.api.manager.MdmFactoryManager
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.util.*

object SwitchOutMdm: ISwitch() {
    private var context: Context? = null
    private val TAG = "SwitchOutMdm"

    fun exit(context: Context) {

    }

    private fun removeDisallowedRunningApp(){
        val mdmFactoryManager = MdmFactoryManager.getInstance()
        val list = mdmFactoryManager.deviceApplicationManager.disallowedRunningApp
        mdmFactoryManager.deviceApplicationManager.removeDisallowedRunningApp(list)
        Log.e(TAG, "remove:${list}")
    }

    private fun recover() {
        val mdmFactoryManager = MdmFactoryManager.getInstance()
        Prefs.setAutoStartSelf(context, false)
        mdmFactoryManager.deviceApplicationManager.setApplicationEnabledSetting("com.huawei.powergenie", PackageManager.COMPONENT_ENABLED_STATE_ENABLED, 1)
        mdmFactoryManager.deviceRestrictionManager.isAdbDisabled = false
        mdmFactoryManager.deviceRestrictionManager.isUSBOtgDisabled = false
        mdmFactoryManager.deviceRestrictionManager.isUSBDataDisabled = false
        mdmFactoryManager.deviceRestrictionManager.isExternalStorageDisabled = false
        mdmFactoryManager.deviceRestrictionManager.isStatusBarExpandPanelDisabled = false

        mdmFactoryManager.deviceSettingsManager.isRestoreFactoryDisabled = false
        mdmFactoryManager.deviceSettingsManager.isSystemUpdateDisabled = false
        
        DisableCompat.enableComponent(context, COMPONENT_UPDATE_SYSTEM)
        DisableCompat.enableComponent(context, EnterprisePrivacySettingsActivity)
    }

    private fun clearProcesses() {
        val dam = MdmFactoryManager.getInstance().deviceApplicationManager
        //clear task
        val runningTasks = dam.getRunningTasks(1000)
        if (runningTasks != null) {
            for (task in runningTasks) {
                val pkg = task.baseActivity.packageName
                if (pkg == context?.packageName || pkg == PkgSecSpace.PACKAGENAME_MIDDLEWARE || pkg == "com.android.systemui") {
                    continue
                }
                dam.removeTask(task.id)
                Log.d(TAG, "remove task " + task.baseActivity.packageName)
            }
        }
        //clear processes
        val runningAppProcesses = dam.runningAppProcesses
        val packages = getAllPackages(PackageManager.MATCH_UNINSTALLED_PACKAGES)
        if (runningAppProcesses != null) {
            for (processInfo in runningAppProcesses) {
                val processName = processInfo.processName
                if (!packages.contains(processName)) {
                    continue
                }
                if (processName == PkgSecSpace.PACKAGENAME_MIDDLEWARE || context?.packageName == processName || processName == "com.huawei.powergenie") {
                    continue
                }
                dam.killApplicationProcess(processName)
                dam.forceStopPackage(processName)
                Log.d(TAG, "kill $processName")
            }
        }
    }

    private fun getAllPackages(flags: Int): List<String> {
        val packageInfos = getAllPackageInfo(flags)
        val list: MutableList<String> = ArrayList()
        for (i in packageInfos.indices) {
            list.add(packageInfos[i].packageName)
        }
        return list
    }

    private fun getAllPackageInfo(flags: Int): List<PackageInfo> {
        return context!!.packageManager.getInstalledPackages(flags)
    }


    private fun killBackgroundApplication() {
        val packageManager: PackageManager? = context?.packageManager
        val mainIntent = Intent(Intent.ACTION_MAIN, null)
        mainIntent.addCategory(Intent.CATEGORY_LAUNCHER)
        val apps = packageManager?.queryIntentActivities(mainIntent, 0)
        for (i in apps?.indices!!) {
            val name = apps[i].activityInfo.packageName
            Log.i(TAG, "killBackgroundApplication: $name")
            if (context?.packageName?.let { name.contains(it) }!! || name == PkgSecSpace.PACKAGENAME_MIDDLEWARE) {
                continue
            }
            MdmFactoryManager.getInstance().deviceApplicationManager.forceStopPackage(name)
        }
    }

    override suspend fun init(context: Context) {
        this.context = context
        MdmFactoryManager.getInstance().deviceApplicationManager.removePersistentApp(getPersistentList(context))
        recover()
        MdmUtils.clearDefaultLauncher(context)
        removeDisallowedRunningApp()
        clearProcesses()
        killBackgroundApplication()
    }
}