import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/foundation.dart';

/// Service untuk mengelola audio player dalam aplikasi
/// Dibuat untuk mengatasi masalah hot reload dengan audioplayers
class AudioService {
  static final AudioService _instance = AudioService._internal();
  factory AudioService() => _instance;

  AudioService._internal() {
    _initialize();
  }

  final AudioPlayer _audioPlayer = AudioPlayer();
  bool _isInitialized = false;
  bool _isPlaying = false;

  void _initialize() {
    if (_isInitialized) return;
    
    _audioPlayer.setReleaseMode(ReleaseMode.release);
    _isInitialized = true;
    
    // Tambahkan listener untuk memastikan release saat hot reload
    _audioPlayer.onPlayerComplete.listen((_) {
      _isPlaying = false;
    });
    
    debugPrint('AudioService: initialized successfully');
  }

  /// Memainkan audio dari asset dengan manajemen resource yang lebih baik
  Future<void> playAsset(String assetPath, {double volume = 0.8}) async {
    if (_isPlaying) {
      await _audioPlayer.stop();
    }
    
    try {
      debugPrint('AudioService: Playing asset $assetPath');
      await _audioPlayer.setVolume(volume);
      await _audioPlayer.play(AssetSource(assetPath));
      _isPlaying = true;
    } catch (e) {
      debugPrint('AudioService: Error playing asset $assetPath - $e');
    }
  }

  /// Menghentikan audio yang sedang diputar
  Future<void> stop() async {
    if (_isPlaying) {
      await _audioPlayer.stop();
      _isPlaying = false;
    }
  }

  /// Dispose untuk membersihkan resource saat tidak digunakan
  void dispose() {
    _audioPlayer.dispose();
    _isInitialized = false;
    _isPlaying = false;
    debugPrint('AudioService: disposed');
  }
} 