import 'dart:io';

import 'package:audioplayers/audioplayers.dart';
import 'package:loopin/IM/im_core.dart';
import 'package:loopin/components/my_toast.dart';

class AudioPlayerService {
  static final AudioPlayerService _instance = AudioPlayerService._internal();
  factory AudioPlayerService() => _instance;
  AudioPlayerService._internal();

  final AudioPlayer _audioPlayer = AudioPlayer();

  /// 播放本地文件
  Future<void> playLocal(String filePath) async {
    try {
      final file = File(filePath);
      if (!file.existsSync()) {
        logger.e('本地音频文件不存在:$filePath');
        MyToast().tip(title: '音频文件不存在');
        return;
      }
      await _audioPlayer.setSourceDeviceFile(filePath);
      await _audioPlayer.resume();
      // 等待播放完成
      await _audioPlayer.onPlayerComplete.first;
    } catch (e) {
      logger.e('播放本地音频失败: $e');
      MyToast().tip(title: '音频文件不存在');
    }
  }

  /// 播放网络音频
  Future<void> playNetwork(String url) async {
    try {
      await _audioPlayer.setSourceUrl(url);
      await _audioPlayer.resume();
      // 等待播放完成
      await _audioPlayer.onPlayerComplete.first;
    } catch (e) {
      logger.e('播放网络音频失败: $e');
      MyToast().tip(title: '音频文件不存在');
    }
  }

  /// 暂停播放
  Future<void> pause() async {
    try {
      await _audioPlayer.pause();
    } catch (e) {
      logger.e('暂停播放失败: $e');
    }
  }

  /// 停止播放
  Future<void> stop() async {
    try {
      await _audioPlayer.stop();
    } catch (e) {
      logger.e('停止播放失败: $e');
    }
  }

  /// 释放资源
  Future<void> dispose() async {
    try {
      await _audioPlayer.dispose();
    } catch (e) {
      logger.e('释放播放器失败: $e');
    }
  }
}
