package com.secspace.lib.common.utils;

import android.Manifest;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.support.v4.content.ContextCompat;
import android.util.Log;

import com.secspace.lib.common.AddDeviceAdminActivity;
import com.secspace.mdmengine.api.annotation.WhichFactory;
import com.secspace.mdmengine.api.manager.MdmFactoryManager;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import static com.secspace.lib.common.env.Packages.CompSecSpace.CLASSNAME_DPM_ADMIN;
import static com.secspace.lib.common.env.Packages.PkgSecSpace.PACKAGENAME_MDMENHANCE;
import static com.secspace.lib.common.env.Packages.PkgSecSpace.PACKAGENAME_MIDDLEWARE;
import static com.secspace.lib.common.env.Packages.PkgSecSpace.PACKAGENAME_SMS_AGENT;
import static com.secspace.lib.common.env.Packages.PkgSecSpace.PACKAGENAME_SYSTEM_AGENT;

/**
 * Created by cyw_m on 2018/3/30.
 */

public class DpmHelper {
    public static final String TAG = "DpmHelper";
    private ComponentName mMiddlewareAdmin;
    private ComponentName mMdmEnhanceAdmin;
    private ComponentName mSelfAdmin;
    private Context mContext;
    private DevicePolicyManager mDpm;
    private static volatile DpmHelper mInstance = null;
    private String MDM_FILE_NAME = "Mdm_Service.apk";
    private MdmFactoryManager mMdmFactoryManager;

    private DpmHelper(Context context) {
        this.mContext = context.getApplicationContext();
        mMiddlewareAdmin = new ComponentName(PACKAGENAME_MIDDLEWARE, CLASSNAME_DPM_ADMIN);
        mMdmEnhanceAdmin = new ComponentName(PACKAGENAME_MDMENHANCE, CLASSNAME_DPM_ADMIN);
        mSelfAdmin = new ComponentName(mContext.getPackageName(), "com.secspace.mdm.dpm.DpmReceiver");
        mDpm = (DevicePolicyManager) mContext.getSystemService(mContext.DEVICE_POLICY_SERVICE);
        mMdmFactoryManager=MdmFactoryManager.getInstance();
    }


    public static DpmHelper getInstance(Context context) {
        if (mInstance == null) {
            synchronized (DpmHelper.class) {
                if (mInstance == null) {
                    mInstance = new DpmHelper(context);
                }
            }
        }
        return mInstance;
    }

    public ComponentName getMiddleWareAdmin() {
        return mMiddlewareAdmin;
    }

    public ComponentName getMdmEnhanceAdmin() {
        return mMdmEnhanceAdmin;
    }

    public ComponentName getSelfAdmin() {
        return mSelfAdmin;
    }

    /**
     * 中间件是否已激活设备管理器
     *
     * @return boolean
     */
    public boolean isMiddlewareDPMActived() {
        return mDpm.isAdminActive(mMiddlewareAdmin);
    }
    public MdmFactoryManager getmMdmFactoryManager(){
        return  mMdmFactoryManager;
    }


    public void initMiddleWare(){
        mMdmFactoryManager.init(mContext, mMiddlewareAdmin);
        mMdmFactoryManager.switchFactory(WhichFactory.HUAWEI);//保证中间件使用华为单系统管控工厂
    }

    /**
     * 中间件2是否已激活设备管理器
     *
     * @return boolean
     */
    public boolean isMdmEnhanceDPMActived() {
        return mDpm.isAdminActive(mMdmEnhanceAdmin);
    }

    /**
     * 安全域是否已激活设备管理器
     *
     * @return boolean
     */
    public boolean isSelfDPMActived() {
        return mDpm.isAdminActive(mSelfAdmin);
    }

    /**
     * 检查中间件是否已安装
     *
     * @return
     */
    public boolean isMiddlewareInstalled() {
        return PkgManager.getInstance(mContext).isAppInstalled(PACKAGENAME_MIDDLEWARE);
    }

    /**
     * 检查中间件2是否已安装
     *
     * @return
     */
    public boolean isMdmEnhanceInstalled() {
        return PkgManager.getInstance(mContext).isAppInstalled(PACKAGENAME_MDMENHANCE);
    }

    /**
     * 检查系统权限代理件是否已安装
     *
     * @return
     */
    public boolean isSystemAgentInstalled() {
        return PkgManager.getInstance(mContext).isAppInstalled(PACKAGENAME_SYSTEM_AGENT);
    }

    /**
     * 跳转到系统激活设备管理器页面
     **/
    public void toActivateMiddlewareDpm() {
     mMdmFactoryManager.getDeviceUserManager().setActiveAdmin(mMiddlewareAdmin);
    }

    /**
     * 跳转到系统激活设备管理器页面
     **/
    public void toActivateMdmEnhanceDpm() {
        Intent intent = new Intent();
        intent.setClass(mContext, AddDeviceAdminActivity.class);
        intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, mMdmEnhanceAdmin);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        mContext.startActivity(intent);
    }

    /**
     * 跳转到系统激活设备管理器页面激活安全域
     **/
    public void toActivateSelfDpm() {
        Intent intent = new Intent();
        intent.setClass(mContext, AddDeviceAdminActivity.class);
        intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, mSelfAdmin);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        mContext.startActivity(intent);
    }

    public boolean isMiddlewareLatest() {
        if (getMiddleWareVersionName().equals("14.0"))
            return true;
        return false;
    }

    public boolean isMdmEnhanceLatest() {
        if (getMdmEnhanceVersionName().equals("9.0"))
            return true;
        return false;
    }

    public boolean isSystemAgentLatest() {
        if (getSystemAgentVersionName().equals("1.7"))
            return true;
        return false;
    }

    public boolean isSmsAgentLatest() {
        if (getSmsAgentVersionName().equals("1.1"))
            return true;
        return false;
    }

    private String getMiddleWareVersionName() {
        return PkgManager.getInstance(mContext).getVersionNameFromPackage(PACKAGENAME_MIDDLEWARE);
    }

    private String getMdmEnhanceVersionName() {
        return PkgManager.getInstance(mContext).getVersionNameFromPackage(PACKAGENAME_MDMENHANCE);
    }

    private String getSystemAgentVersionName() {
        return PkgManager.getInstance(mContext).getVersionNameFromPackage(PACKAGENAME_SYSTEM_AGENT);
    }

    private String getSmsAgentVersionName() {
        return PkgManager.getInstance(mContext).getVersionNameFromPackage(PACKAGENAME_SMS_AGENT);
    }

    public int getSecSpaceVersionCode() {
        return PkgManager.getInstance(mContext).getVersionCodeFromPackage(mContext.getPackageName());
    }

    public boolean isMiddlewareDeviceOwner() {
        boolean isDeviceOwnerApp = mDpm.isDeviceOwnerApp(PACKAGENAME_MIDDLEWARE);
        Log.i(TAG, "is Middleware Device Owner? " + isDeviceOwnerApp);
        return isDeviceOwnerApp;
    }

    public boolean isMdmEnhanceDeviceOwner() {
        boolean isDeviceOwnerApp = mDpm.isDeviceOwnerApp(PACKAGENAME_MDMENHANCE);
        Log.i(TAG, "is MdmEnhance Device Owner? " + isDeviceOwnerApp);
        return isDeviceOwnerApp;
    }

    public boolean isMiddlewareProfileOwner() {
        boolean isProfileOwner = mDpm.isProfileOwnerApp(PACKAGENAME_MIDDLEWARE) || mDpm.isDeviceOwnerApp(PACKAGENAME_MIDDLEWARE);
        Log.i(TAG, "is Middleware Profile Owner? " + isProfileOwner);
        return isProfileOwner;
    }

    public boolean middlewareHaveSystemPermissions() {
        boolean result = ContextCompat.checkSelfPermission(mContext, Manifest.permission.INSTALL_PACKAGES)
                == PackageManager.PERMISSION_GRANTED
                && ContextCompat.checkSelfPermission(mContext, Manifest.permission.DELETE_PACKAGES)
                == PackageManager.PERMISSION_GRANTED;
        Log.i(TAG, "middleware Have System Permissions?  " + result);
        return result;
    }


    public boolean isSecSpaceDeviceOwner() {
        boolean isDeviceOwnerApp = mDpm.isDeviceOwnerApp(mContext.getPackageName());
        Log.i(TAG, "is Middleware Device Owner? " + isDeviceOwnerApp);
        return isDeviceOwnerApp;
    }

    public boolean isSecSpaceProfileOwner() {
        boolean isProfileOwner = mDpm.isProfileOwnerApp(mContext.getPackageName());
        Log.i(TAG, "is Middleware Profile Owner? " + isProfileOwner);
        return isProfileOwner;
    }

    public void clearSecSpaceDeviceOwner() {
        mDpm.clearDeviceOwnerApp(mContext.getPackageName());
    }

    public boolean hideApplication(String pkg, boolean hide) {
        boolean result = false;
        if (isMiddlewareDeviceOwner()) {
            result = mDpm.setApplicationHidden(getMdmEnhanceAdmin(), pkg, hide);
        }
        Log.i(TAG, "hideApplication pkg: " + pkg + " hide:" + hide + " result:" + result);
        return result;
    }

    public void installMiddleWare() {
        String appStoreFilePath = mContext.getExternalCacheDir() + File.separator + MDM_FILE_NAME;
        File file = new File(appStoreFilePath);
        if (file.exists()) {
            file.delete();
        }
        copyApkFromAssets(mContext, MDM_FILE_NAME, appStoreFilePath);
        installByInstaller(appStoreFilePath);
    }

    public void  preinstallApp(String apkName){
        String appStoreFilePath = mContext.getExternalCacheDir().getPath() + File.separator + apkName;
        Log.i(TAG, "installTool: "+appStoreFilePath);
        File file = new File(appStoreFilePath);
        if (file.exists()) {
            file.delete();
        }
        copyApkFromAssets(mContext, apkName, appStoreFilePath);
        int storageApkVersionCode = PkgManager.getInstance(mContext).getStorageApkVersionCode(appStoreFilePath);
        int versionCodeFromPackage = PkgManager.getInstance(mContext).getVersionCodeFromPackage(PkgManager.getInstance(mContext).getStorageApkPackgeName(appStoreFilePath));
        Log.i(TAG, "preinstallApp storageApkVersionCode : "+storageApkVersionCode);
        Log.i(TAG, "preinstallApp versionCodeFromPackage : "+versionCodeFromPackage);
        if (storageApkVersionCode>versionCodeFromPackage){
            MdmFactoryManager.getInstance().getDeviceApplicationManager().installPackage(appStoreFilePath);
        }
    }

    /**
     * 安装中间件
     *
     * @param path
     */
    private void installByInstaller(String path) {
        Log.i(TAG, "installByInstaller: " + path);
        Intent i = new Intent(Intent.ACTION_VIEW);
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        i.setDataAndType(path.contains("file://") ? Uri.parse(path) : Uri.parse("file://" + path), "application/vnd.android.package-archive");
        mContext.startActivity(i);
//        File file=new File(path);
//        if (file != null) {
//            Intent intent = new Intent(Intent.ACTION_VIEW);
//            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//                intent.setDataAndType(FileProvider.getUriForFile(mContext, mContext.getPackageName() + ".fileprovider", file), "application/vnd.android.package-archive");
//                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
//            } else {
//                intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
//            }
//            mContext.startActivity(intent);
//        }
    }


    private boolean copyApkFromAssets(Context context, String fileName, String path) {
        boolean copyIsFinish = false;
        try {
            InputStream is = context.getAssets().open(fileName);
            File file = new File(path);
            file.createNewFile();
            FileOutputStream fos = new FileOutputStream(file);
            byte[] temp = new byte[1024];
            int i = 0;
            while ((i = is.read(temp)) > 0) {
                fos.write(temp, 0, i);
            }
            fos.close();
            is.close();
            copyIsFinish = true;

        } catch (IOException e) {
            e.printStackTrace();
        }
        return copyIsFinish;
    }
}
