import { abilityAccessCtrl, bundleManager, PermissionRequestResult, Permissions } from '@kit.AbilityKit';

export class PermissionControl {
  private declare static instance: PermissionControl
  private tokenID: number = 0
  //记录已申请权限，方便到时候调用checkPermission时传参
  private permissions: Permissions[] = []
  //上一次使用checkPermission校验的权限
  private lastPermission?: Permissions
  private context?: Context
  private atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager();

  private constructor() {
  }

  static getInstance() {
    if (!PermissionControl.instance) {
      PermissionControl.instance = new PermissionControl()
    }
    return PermissionControl.instance
  }

  //TODO 需要在windowStage中初始化
  async init(context: Context) {
    this.context = context
    const res = await bundleManager.getBundleInfoForSelf(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION)
    this.tokenID = res.appInfo.accessTokenId
  }

  //申请权限
  askPermission(permissions: Permissions[], callback: (res?: PermissionRequestResult, err?: Error) => void) {
    this.permissions = permissions
    this.atManager.requestPermissionsFromUser(this.context, permissions, (err, data) => {
      if (!err && data) {
        callback(data)
      } else {
        callback(undefined, err)
      }
    })
  }

  //二次申请权限 不传参数就是上次校验的权限
  secondAskPermission(permission: Permissions | undefined = this.lastPermission) {
    if (permission) {
      this.atManager.requestPermissionOnSetting(this.context, this.permissions)
    }
  }

  //校验权限
  checkPermission(permission: Permissions) {
    const isPermission = this.atManager.checkAccessTokenSync(this.tokenID, permission)
    this.lastPermission = permission
    if (isPermission == -1) {
      return false
    }
    return true
  }
}

export const permissionController = PermissionControl.getInstance()
