import 'dart:io';

import 'package:file_picker/file_picker.dart';
import 'package:photo_manager/photo_manager.dart';

class AudioPickerUtils {
  AudioPickerUtils._();

  static const List<String> allowFileType = [
    'wav',
    'mp3',
    'm4a',
    'flv',
    'mp4',
    'wma',
    '3gp',
    'amr',
    'aac',
    'ogg-opus',
    'flac'
  ];

  //申请权限
  static Future<bool> requestPermissionExtend() async {
    final PermissionState ps = await PhotoManager.requestPermissionExtend(
        requestOption: const PermissionRequestOption(
            androidPermission: AndroidPermission(
      type: RequestType.audio,
      mediaLocation: false,
    )));
    return ps.hasAccess;
  }

  //是否有权限
  static Future<bool> hasPermission() async {
    final PermissionState ps = await PhotoManager.getPermissionState(
        requestOption: const PermissionRequestOption());
    return ps.hasAccess;
  }

  //获取AssetPathEntity
  static Future<List<AssetPathEntity>> getAssetPathList() async {
    final PMFilter filter = FilterOptionGroup(
      audioOption: const FilterOption(
        sizeConstraint: SizeConstraint(ignoreSize: true),
      ),
    );
    final List<AssetPathEntity> paths = await PhotoManager.getAssetPathList(
      onlyAll: true,
      type: RequestType.audio,
      filterOption: filter,
    );
    return paths;
  }

  //获取本地音频资源列表
  static Future<List<AssetEntity>> getAssetListPaged(
      AssetPathEntity path, int page, int size) async {
    final List<AssetEntity> entities = await path.getAssetListPaged(
      page: page,
      size: size,
    );
    return entities;
  }

  static Future<List<AssetEntity>> getAssetListRange(
      AssetPathEntity path, int offset, int limit) async {
    final List<AssetEntity> entities = await path.getAssetListRange(
      start: offset,
      end: offset + limit,
    );
    return entities;
  }

  //根据id获取AssetEntity
  static Future<AssetEntity?> getAssetEntity(String? id) async {
    if (id == null) {
      return null;
    }
    return await AssetEntity.fromId(id);
  }

  //根据id获取文件
  static Future<File?> getAssetFile(String? id) async {
    if (id == null) {
      return null;
    }
    AssetEntity? assetEntity = await AssetEntity.fromId(id);
    return await assetEntity?.file;
  }

  //通过平台文件管理器的方式选择单一文件
  static Future<File?> pickSingleFileByPlatform(
      {List<String> type = allowFileType}) async {
    FilePickerResult? result = await FilePicker.platform
        .pickFiles(type: FileType.custom, allowedExtensions: type);
    if (result != null) {
      String filePath = result.files.single.path!;
      File file = File(filePath);
      return file;
    }
    return null;
  }
}
