package com.android.launcher3.mdm;

import android.accounts.AccountManager;
import android.accounts.AuthenticatorDescription;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.UserInfo;
import android.support.annotation.StringDef;
import android.text.TextUtils;
import android.util.Log;

import com.secspace.lib.common.env.Packages;
import com.secspace.lib.common.utils.DpmHelper;
import com.secspace.mdmengine.api.manager.MdmFactoryManager;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;


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

    private static final String TAG = "DpmOwnerHelper";

    private static boolean isSettingDeviceOwner = false;

    private static List<String> disabledApps = new ArrayList<>();

    /**
     * 禁用账户并且移除掉所有其他用户（华为账号，隐私空间，工作空间等）
     */
    public static void disableAccountsAndRemoveProfileUsers(final Context context) {
        Log.i(TAG, "disableAccountsAndRemoveProfileUsers: 移除用户是否正在设置=" + isSettingDeviceOwner);
        if (isSettingDeviceOwner) {
            return;
        }
        isSettingDeviceOwner = true;

        try {
            AccountManager accountManager = (AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE);
            disabledApps.clear();
            //此方法必须在主线程中调用
            AuthenticatorDescription[] authenticatorTypes = accountManager.getAuthenticatorTypes();
            if (authenticatorTypes != null && authenticatorTypes.length > 0) {
                for (AuthenticatorDescription authenticatorDescription : authenticatorTypes) {
                    try {
                        PackageInfo pi = context.getPackageManager().getPackageInfo(authenticatorDescription.packageName, 0);
                        // 如果安装，则禁用
                        DisableCompat.disableApplication(context, authenticatorDescription.packageName);
                        disabledApps.add(pi.packageName);
                    } catch (PackageManager.NameNotFoundException e) {
                        e.printStackTrace();
                    }
                }
            }

            MdmFactoryManager.getInstance().getDeviceUserManager().setAddUserDisabled(true);
            List<UserInfo> users = MdmFactoryManager.getInstance().getDeviceUserManager().getSystemUserList();
            if (users != null && users.size() > 0) {
                for (UserInfo userInfo : users) {
                    if (!userInfo.isPrimary()) {
                        // 移除所有其他用户
                        MdmFactoryManager.getInstance().getDeviceUserManager().removeUser(userInfo.id);
                    }
                }
            }

            Disposable subscribe = Observable.just(context).observeOn(Schedulers.newThread())
                    .subscribe(new Consumer<Context>() {
                        @Override
                        public void accept(Context context) throws Exception {
                            setDeviceowner(context);
                        }
                    });

        } catch (Exception e) {
            Log.i(TAG, "disableAccountsAndRemoveProfileUsers: " + e.getMessage());
            e.printStackTrace();
            isSettingDeviceOwner = false;
        }
    }

    private static int COUNT = 0;

    private static void setDeviceowner(Context context) throws InterruptedException {
        COUNT++;
        if (COUNT < 4) {
            MdmFactoryManager.getInstance().getDeviceRestrictionManager().setDeviceOwnerApp(Packages.PkgSecSpace.PACKAGENAME_MIDDLEWARE);
            if (!DpmHelper.getInstance(context).isMiddlewareDeviceOwner()) {
                Log.i(TAG, "disableAccountsAndRemoveProfileUsers: 设置失败！");
                Thread.sleep(3000);
                setDeviceowner(context);
            } else {
                recoverAccounts(context);
                isSettingDeviceOwner = false;
                COUNT = 0;
                Log.i(TAG, "disableAccountsAndRemoveProfileUsers: 设置成功！");
            }
        } else {
            Log.i(TAG, "disableAccountsAndRemoveProfileUsers: 到达尝试次数！");
            recoverAccounts(context);
            isSettingDeviceOwner = false;
            COUNT = 0;
        }
    }


    /**
     * 恢复禁用的账户
     */
    private static void recoverAccounts(Context context) {
        MdmFactoryManager.getInstance().getDeviceUserManager().setAddUserDisabled(false);
        if (disabledApps != null && disabledApps.size() > 0) {
            for (String disableApp : disabledApps) {
                if (!TextUtils.isEmpty(disableApp)) {
                    DisableCompat.enableApplication(context, disableApp.trim());
                }
            }
            //清空文件
            disabledApps.clear();
        }
    }
}

