import 'camera_command.dart';

mixin VoiceCommand on CameraCommand {
  Future<bool> _startSoundCgi(bool bSupportg711a, {int count = 0}) async {
    final ret = bSupportg711a
        ? await writeCgi("audiostream.cgi?streamid=7&")
        : await writeCgi("audiostream.cgi?streamid=1&adpcm_ver=1&");
    if (!ret) return false;
    final value = await waitCommandResult((cmd, data) {
      return cmd == 24625;
    }, 3);
    if (!value.isSuccess && count < 3) {
      return _startSoundCgi(bSupportg711a, count: count + 1);
    }
    return value.isSuccess;
  }

  Future<bool> _stopSoundCgi({int count = 0}) async {
    final ret = await writeCgi("audiostream.cgi?streamid=16&");
    if (!ret) return false;
    final value = await waitCommandResult((cmd, data) {
      return cmd == 24625;
    }, 3);
    if (!value.isSuccess && count < 3) {
      return _stopSoundCgi(count: count + 1);
    }
    return value.isSuccess;
  }

  bool supportG711() {
    return statusResult!.support_audio_g711a != null &&
        statusResult!.support_audio_g711a != "0";
  }

  bool supportbothWay() {
    return statusResult!.EchoCancellationVer != null &&
        statusResult!.EchoCancellationVer != "0";
  }

  Future<bool> startSoundStream() async {
    return await _startSoundCgi(supportG711());
  }

  Future<bool> stopSoundStream() async {
    return await _stopSoundCgi();
  }

  @override
  Future<void> deviceDestroy() async {
    super.deviceDestroy();
  }
}
