import abilityAccessCtrl from "@ohos:abilityAccessCtrl";
import bundleManager from "@ohos:bundle.bundleManager";
import type { PermissionRequestResult, Permissions } from "@ohos:abilityAccessCtrl";
import JSON from "@ohos:util.json";
const TAG = '[PermissionsUtils]';
/*权限工具类*/
export class PermissionsUtils {
    public static async checkAccessToken(permission: Permissions): Promise<abilityAccessCtrl.GrantStatus> {
        let atManager = abilityAccessCtrl.createAtManager();
        let grantStatus: abilityAccessCtrl.GrantStatus = -1;
        // 1. 获取应用程序的 tokenId
        let tokenId: number = 0;
        try {
            let bundleInfo = await bundleManager.getBundleInfoForSelf(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION);
            let appInfo = bundleInfo.appInfo;
            tokenId = appInfo.accessTokenId;
        }
        catch (e) {
            console.error(TAG, `Failed to get bundle info for self. Code is ${e.code}, message is ${e.message}`);
        }
        // 2. 查询权限
        try {
            grantStatus = await atManager.checkAccessToken(tokenId, permission);
        }
        catch (e) {
            console.error(TAG, `Failed to check access token. Code is ${e.code}, message is ${e.message}`);
        }
        return grantStatus;
    }
    public static async reqPermissionsFromUser(context: Context, permissionList: Array<Permissions>): Promise<number[]> {
        let atManager = abilityAccessCtrl.createAtManager();
        let grantStatus: PermissionRequestResult = {
            permissions: [],
            authResults: []
        };
        try {
            grantStatus = await atManager.requestPermissionsFromUser(context, permissionList);
        }
        catch (e) {
            console.error(TAG, `Failed to request permission. Code is ${e.code}, message is ${e.message}`);
        }
        return grantStatus.authResults;
    }
    public static async getBundleName(): Promise<string> {
        try {
            let bundleInfo = await bundleManager.getBundleInfoForSelf(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION);
            let appInfo = bundleInfo.appInfo;
            console.debug(TAG, 'bundleInfo:' + JSON.stringify(bundleInfo));
            console.debug(TAG, 'appInfo   :' + JSON.stringify(appInfo));
            return bundleInfo.name;
        }
        catch (e) {
            console.error(TAG, `Failed to get bundle info for self. Code is ${e.code}, message is ${e.message}`);
        }
        return '';
    }
}
