import 'package:permission_handler/permission_handler.dart';

class PermissionService {
  PermissionService._();

  static Future<bool> request(Permission permission) async {
    final status = await permission.status;
    if (status.isGranted || status.isLimited) return true;

    final next = await permission.request();
    return next.isGranted || next.isLimited;
  }

  static Future<Map<Permission, PermissionStatus>> requestAll(
    Iterable<Permission> permissions,
  ) {
    return permissions.toList().request();
  }

  /// 仅对尚未授予的权限发起系统授权弹窗，已授予则直接返回当前状态。
  static Future<Map<Permission, PermissionStatus>> requestMissing(
    Iterable<Permission> permissions,
  ) async {
    final result = <Permission, PermissionStatus>{};
    for (final permission in permissions) {
      final current = await permission.status;
      if (current.isGranted ||
          current.isLimited ||
          current.isPermanentlyDenied) {
        result[permission] = current;
        continue;
      }
      result[permission] = await permission.request();
    }
    return result;
  }

  static Future<bool> ensure(
    Permission permission, {
    bool openSettingsWhenPermanentlyDenied = true,
  }) async {
    final granted = await request(permission);
    if (granted) return true;

    final status = await permission.status;
    if (openSettingsWhenPermanentlyDenied && status.isPermanentlyDenied) {
      await openAppSettings();
    }
    return false;
  }
}
