import 'package:just_audio/just_audio.dart';

abstract class AudioService {
  Future<void> playTone({required String path, bool isMute = false});

  Future<void> listenAudioPlayerEvents({required Function() onToneCompleted});

  Future<void> disposeAudioPlayer();
}

class AudioServiceImp implements AudioService {
  AudioPlayer audioPlayerInstance;

  AudioServiceImp({required this.audioPlayerInstance});

  @override
  Future<void> listenAudioPlayerEvents({required Function() onToneCompleted}) async {
    audioPlayerInstance.playerStateStream.listen((playerState) async {
      if (playerState.processingState == ProcessingState.completed) {
        onToneCompleted();
      }
    });
  }

  @override
  Future<void> playTone({required String path, bool isMute = false}) async {
    audioPlayerInstance.setAsset(path);
    if (isMute) {
      audioPlayerInstance.setVolume(0.0);
    } else {
      audioPlayerInstance.setVolume(1.0);
    }
    await audioPlayerInstance.play();
  }

  @override
  Future<void> disposeAudioPlayer() async {
    await audioPlayerInstance.dispose();
  }
}
