// Author: fengshengxiong
// Date: 2024/6/4
// Description: 文件工具类

import 'dart:io';

import 'package:flutter/services.dart';
import 'package:tone_snap/utils/local_path_util.dart';
import 'package:tone_snap/utils/log_util.dart';

class FileUtil {
  /// Assets文件复制到getAssetsDir目录下
  static Future<String> getAssetsToFilePath(String assets) async {
    final byteData = await rootBundle.load(assets);
    final file = File('${(await LocalPathUtil.getAssetsDir()).path}/${assets.split('/').last}');
    await file.create(recursive: true);
    await file.writeAsBytes(byteData.buffer.asUint8List(byteData.offsetInBytes, byteData.lengthInBytes));
    return file.path;
  }

  /// 删除目录中的所有文件
  static Future<void> deleteAllFilesInDirectory(Directory directory) async {
    if (await directory.exists()) {
      final files = directory.listSync();

      for (var file in files) {
        if (file is File) {
          try {
            await file.delete();
            LogUtil.d('Deleted file: ${file.path}');
          } catch (e) {
            LogUtil.d('Error deleting file: ${file.path}, Error: $e');
          }
        }
      }
    } else {
      LogUtil.d('Directory does not exist: ${directory.path}');
    }
  }
}