import 'package:permission_handler/permission_handler.dart';

import 'interfaces/permission.dart';

class PermissionManager implements IPermissionManager {
  PermissionManager();

  @override
  Future<bool> requestLocationPermission() async {
    PermissionStatus status = await Permission.location.request();
    if (status.isGranted) {
      return true;
    } else {
      return false;
    }
  }

  @override
  Future<bool> requestBluetoothConnectPermission() async {
    PermissionStatus status = await Permission.bluetoothConnect.request();
    if (status.isGranted) {
      return true;
    } else {
      return false;
    }
  }

  @override
  Future<bool> requestBluetoothScanPermission() async {
    PermissionStatus status = await Permission.bluetoothScan.request();
    if (status.isGranted) {
      return true;
    } else {
      return false;
    }
  }

  @override
  Future<bool> requestBluetoothAdvertisePermission() async {
    PermissionStatus status = await Permission.bluetoothAdvertise.request();
    if (status.isGranted) {
      return true;
    } else {
      return false;
    }
  }

  @override
  Future<bool> requestInstallPackagesPermission() async {
    PermissionStatus status = await Permission.requestInstallPackages.request();
    if (status.isGranted) {
      return true;
    } else {
      return false;
    }
  }

  @override
  Future<bool> requestCameraPermissions() async {
    var status = await Permission.camera.status;
    if (status.isGranted) {
      return true;
    } else {
      PermissionStatus status = await Permission.camera.request();
      if (status.isGranted) {
        return true;
      }
    }
    return false;
  }

  Map<String, Future<bool> Function()> get perMissionMap {
    return {
      'Location': requestLocationPermission,
      'BluetoothConnect': requestBluetoothConnectPermission,
      'BluetoothScan': requestBluetoothScanPermission,
      'BluetoothAdvertise': requestBluetoothAdvertisePermission,
      'Camera': requestCameraPermissions,
      'InstallPackages': requestInstallPackagesPermission,
    };
  }

  ///批量获取权限
  @override
  Future<bool> requestPermissions(List<String> permissions) async {
    List<String> unauthorizedPermissions = [];
    for (var element in permissions) {
      var functionToCall = perMissionMap[element];
      if (functionToCall != null) {
        var result = await functionToCall();
        if (!result) {
          unauthorizedPermissions.add(element);
        }
      }
    }
    if (unauthorizedPermissions.isNotEmpty) {
      return false;
    }
    return true;
  }

  @override
  Future<bool> openAppSettingsAsync() async {
    return await openAppSettings();
  }
}

enum PermissionEnum {
  //音视频相关
  VideoAndVoiceRelevant,

  //IO相关
  IORelevant,

  //App 需要的所有权限
  All,
}
