import 'package:permission_handler/permission_handler.dart';
import 'package:device_info_plus/device_info_plus.dart';
import 'dart:io';

import 'log/logger.dart';

class PermissionManager {
  /// 检查是否需要请求存储权限
  static Future<bool> _needsStoragePermission() async {
    if (!Platform.isAndroid) return false;

    try {
      final androidInfo = await DeviceInfoPlugin().androidInfo;
      // Android 10 是 API 29，所以 API 28 及以下是 Android 9 及以下
      return androidInfo.version.sdkInt <= 29;
    } catch (e) {
      log('PermissionManager', 'Error checking Android version: $e');
      return false;
    }
  }

  /// 请求存储权限
  static Future<bool> requestStoragePermission() async {
    // 检查是否需要请求权限
    if (!await _needsStoragePermission()) {
      return true;
    }

    try {
      var status = await Permission.storage.status;

      if (status.isGranted) {
        return true;
      }

      if (status.isPermanentlyDenied) {
        await openAppSettings();
        return false;
      }

      status = await Permission.storage.request();
      return status.isGranted;
    } catch (e) {
      log('PermissionManager', 'Error requesting storage permission: $e');
      return false;
    }
  }

  /// 检查存储权限
  static Future<bool> checkStoragePermission() async {
    // 检查是否需要请求权限
    if (!await _needsStoragePermission()) {
      return true;
    }

    try {
      final status = await Permission.storage.status;
      return status.isGranted;
    } catch (e) {
      log('PermissionManager', 'Error checking storage permission: $e');
      return false;
    }
  }
}
