import { abilityAccessCtrl, Permissions, bundleManager, common, Context, Want } from '@kit.AbilityKit'

/*
 * 权限工具类
 * EZOpenSDK
 *
 * Created by swd on 2024/5/14.
 * Copyright (c) 2024年 Ezviz. All rights reserved.
 */
export default class PermissionUtil {
  //检查并获取权限
  static async checkAndRequestPermission(context: Context, permissionList: Permissions[]): Promise<boolean> {
    let grantedAll = true
    let grantStatus: number[] = await PermissionUtil.requestPermission(context, permissionList)
    for (let index = 0; index < grantStatus.length; index++) {
      if (grantStatus[index] === abilityAccessCtrl.GrantStatus.PERMISSION_DENIED) {
        grantedAll = false
      }
    }
    return Promise.resolve(grantedAll)
  }

  //直接获取权限
  static async requestPermission(context: Context, permissionList: Permissions[]): Promise<number[]> {
    let requestResult = await abilityAccessCtrl.createAtManager().requestPermissionsFromUser(context, permissionList)
    return requestResult.authResults
  }

  //跳转到系统设置
  //用户拒绝授权，则需要提示用户必须授权才能访问当前页面的功能，并引导用户到系统设置中打开相应的权限
  static openPermissionSettings(context: Context) {
    let params: Record<string, Object> = {
      "settingsParamBundleName": `${context.applicationInfo.name}`
    }
    let wantInfo: Want = {
      bundleName: 'com.huawei.hmos.settings',

      abilityName: 'com.huawei.hmos.settings.MainAbility',

      uri: 'application_info_entry',

      parameters: params
    }
    let abilityContext = getContext() as common.UIAbilityContext
    abilityContext.startAbility(wantInfo).then(() => {
      console.debug('location open setting page')
    }).catch((_: string) => {
      console.debug('location open setting page failed')
    })
  }

  //引导用户跳转到系统设置的弹窗
  static showGuideToSettingsDialog(context: Context, title: string, message: string) {
    AlertDialog.show(
      {
        title: title,
        message: message,
        autoCancel: true,
        alignment: DialogAlignment.Bottom,
        gridCount: 4,
        offset: {
          dx: 0, dy: -20
        },
        primaryButton: {
          value: '取消',
          action: () => {
            console.info('Callback when the first button is clicked')
          }
        },
        secondaryButton: {
          value: '去设置',
          action: () => {
            console.info('Callback when the second button is clicked')
            PermissionUtil.openPermissionSettings(context)
          }
        },
        cancel: () => {
          console.info('Closed callbacks')
        }
      }
    )
  }
}




