import 'package:audioplayer/audioplayer.dart';
import 'package:chat/data/constants.dart';
import 'package:chat/utils/sp_utils.dart';
import 'package:flutter/widgets.dart';

class SoundUtils {
  // 工厂模式
  factory SoundUtils() => _getInstance();

  static SoundUtils get instance => _getInstance();
  static SoundUtils _instance;

  String curSoundUrl;

  Map<String, bool> soundStateMap = {};

  SoundUtils._internal() {
    // 初始化
    audioPlugin = new AudioPlayer();
    stateStream = audioPlugin.onPlayerStateChanged;
  }

  AudioPlayer audioPlugin;
//  AudioCache audioCache = AudioCache();
  Stream<AudioPlayerState> stateStream;
  bool isPlaying(url) {
    return soundStateMap[url] ?? false;
  }

  static SoundUtils _getInstance() {
    if (_instance == null) {
      _instance = new SoundUtils._internal();
    }
    return _instance;
  }


  initPlayMode() async {
    bool playMode = await SPUtils.getBool(Constants.SOUND_PLAY_MODE);
    if (playMode != null && playMode) {
      setReceiver(true);
    } else {
      setReceiver(false);
    }
  }

  savePlayModeConfig(bool playMode) async {
    await SPUtils.saveBool(Constants.SOUND_PLAY_MODE, playMode);
    setReceiver(playMode);
  }

  ///设置听筒true 设置外放false
  setReceiver(bool setReceiver) async {
    await audioPlugin.setReceiver(setReceiver);
  }

  play(url,
      {bool isLocal = true,
      VoidCallback onPlayed,
      VoidCallback complete}) async {
    if (curSoundUrl != null && curSoundUrl != url) {
      print('不是同一个音频文件');
      await stop();
    }
    print('播放url:$url');
    await audioPlugin.play(url, isLocal: isLocal);

    curSoundUrl = url;
    stateStream.listen((state) {
      if (state == AudioPlayerState.PLAYING) {
        soundStateMap[curSoundUrl] = true;
        if (onPlayed != null) {
          onPlayed();
        }
      } else {
        soundStateMap[curSoundUrl] = false;

        if (complete != null) {
          complete();
        }
      }
    });
  }

  pause() async {
    print('暂停播放');
    if (curSoundUrl != null) {
      soundStateMap[curSoundUrl] = false;
      await audioPlugin.pause();
    }
  }

  stop() async {
    if (curSoundUrl != null) {
      soundStateMap[curSoundUrl] = false;
      await audioPlugin.stop();
    }
  }
}
