package com.secspace.lib.common.function

import android.accounts.AccountManager
import android.content.Context
import android.content.pm.PackageManager
import android.os.Environment
import android.os.Handler
import com.secspace.lib.common.utils.DisableCompat
import com.secspace.lib.common.utils.IntentUtil
import com.secspace.log.Log
import com.secspace.mdmengine.api.manager.MdmFactoryManager
import java.io.File
import java.io.FileReader
import java.io.FileWriter

/**
 * Created by lichuanzhi@tiankuan.net on 2019/3/29
 */
object DpmOwnerHelper {

    private const val TAG = "DpmOwnerHelper"
    private const val DISABLED_ACCOUNT_APP_FILE = "disableAccountApps.txt"

    var isSettingDeviceOwner = false;

    private val mHandler = Handler()

    /**
     * 禁用账户并且移除掉所有其他用户（华为账号，隐私空间，工作空间等）
     */
    fun disableAccountsAndRemoveProfileUsers(context: Context) {
        if (isSettingDeviceOwner) {
            return
        }
        isSettingDeviceOwner = true
        try {
            val accountManager = context.getSystemService(Context.ACCOUNT_SERVICE) as AccountManager
            val disabledApps = ArrayList<String>()
            val map = HashMap<String, String>()
            accountManager.authenticatorTypes.forEach {
                map[it.type] = it.packageName
                Log.d(TAG, "authenticatorTypes:${it.type}, ${it.packageName}")
            }
            accountManager.accounts.forEach {
                try {
                    Log.d(TAG, "accounts:${map.keys}, ${it.type}")
                    if (map.keys.contains(it.type)){
                        map[it.type]?.let {
                            pkg -> disabledApps.add(pkg)
                            DisableCompat.disableApplication(context, pkg)
                        }
                    }
                } catch (e: PackageManager.NameNotFoundException) {
                    e.printStackTrace()
                }
            }
            if (disabledApps.size > 0) {
                writeDisabledApps(context, disabledApps)
            }
            //MdmFactoryManager.getInstance().deviceUserManager.isAddUserDisabled = true
            val users = MdmFactoryManager.getInstance().deviceUserManager.systemUserList
            users?.forEach {
                if (!it.isPrimary) {
                    // 移除所有其他用户
                    MdmFactoryManager.getInstance().deviceUserManager.removeUser(it.id)
                }
            }
            mHandler.postDelayed({
                IntentUtil.activateMdmServiceDeviceOwner(context)
                isSettingDeviceOwner = false
            }, 8 * 1000)

            mHandler.postDelayed({
                recoverAccounts(context)
            }, 10 * 1000)
        } catch (e: Exception) {
            Log.e(TAG, Log.getStackTraceString(e))
            isSettingDeviceOwner = false
        }
    }

    /**
     * 恢复禁用的账户
     */
    fun recoverAccounts(context: Context) {
        try {
            val disabledApps = readDisabledApps(context)
            disabledApps?.map {
                if (it.trim().isNotEmpty()) {
                    DisableCompat.enableApplication(context, it.trim())
                }
            }
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
        }
    }

    private fun writeDisabledApps(context: Context, disabledApps: List<String>) {
        val dir = File(Environment.getExternalStorageDirectory().absolutePath + File.separator + "." + context.packageName)
        if (!dir.exists()) {
            dir.mkdirs()
        }
        val writer = FileWriter(File(dir, DISABLED_ACCOUNT_APP_FILE), false)
        writer.write(disabledApps.joinToString())
        writer.close()
    }

    private fun readDisabledApps(context: Context): List<String>? {
        val dir = File(Environment.getExternalStorageDirectory().absolutePath + File.separator + "." + context.packageName)
        if (!dir.exists()) {
            return null
        }
        val file = File(dir, DISABLED_ACCOUNT_APP_FILE)
        if (!file.exists()) {
            return null
        }
        return FileReader(file).readText().split(",")
    }

    fun removeOtherUsers(){
        val users = MdmFactoryManager.getInstance().deviceUserManager.systemUserList
        users?.forEach {
            if (!it.isPrimary) {
                // 移除所有其他用户
                MdmFactoryManager.getInstance().deviceUserManager.removeUser(it.id)
            }
        }
    }
}