/// Created by Haoyi on 2022/8/25

part of 'audio_effector.dart';

abstract class AudioBundle {
  String get name;

  Map<AudioEffect, Audio> get audios;

  Completer<bool>? _loadedCompleter;

  Future load() async {
    final completer = _loadedCompleter;
    if (completer != null) {
      Log.w("already loading, waiting... ${completer.isCompleted}");
      if (completer.isCompleted) {
        return;
      }
      return completer.future;
    }
    _loadedCompleter = Completer<bool>();

    final sources = audios.values.map((a) => a.load).toList();
    for (var source in sources) {
      try {
        await source.call();
      } catch (error, stacktrace) {
        Log.w("load audio error! $error",
            tag: "audio", stackTrace: stacktrace, syncCrashlytics: true);
      }
    }
    _loadedCompleter?.complete(true);
    _loadedCompleter = null;
  }

  void dispose() {
    for (var audio in audios.values) {
      audio.dispose();
    }
  }
}
