import RtcEngine from 'react-native-agora';

export const onTalkCall = async data => {
  try {
    if (!this.engine) {
      //创建 RtcEngine 实例
      this.engine = await RtcEngine.create(data.appid);
    }
    await this.engine.disableVideo(true); // 关闭视频模块
    await this.engine.enableLocalAudio(false); //调用 enableLocalAudio(false) 关闭本地采集后，系统会走媒体音量
    await this.engine.muteAllRemoteAudioStreams(false); //停止/恢复接收所有音频流。
    await this.engine.setDefaultMuteAllRemoteAudioStreams(false); // 设置是否默认接收音频流
    await this.engine.setDefaultMuteAllRemoteVideoStreams(true); // 设置是否默认接收视频流
    await this.engine.disableVideo(); //关闭视频模块
    await this.engine.setAudioProfile(4, 3); //设置音频编码配置
    await this.engine.adjustPlaybackSignalVolume(400); //调节本地播放的所有远端用户音量
    await this.engine.adjustAudioMixingPlayoutVolume(100); //调节音乐文件的本地播放音量
    await this.engine.setDefaultAudioRoutetoSpeakerphone(true); //默认从外放（扬声器）出声
    //监听
    // this.engine.addListener('Warning', data => {
    //   console.log('Warning' + data);
    // });
    // this.engine.addListener('Error', data => {
    //   console.log('Error' + data);
    // });
    // this.engine.addListener('JoinChannelSuccess', data => {
    //   console.warn('JoinChannelSuccess' + data);
    // });
    // this.engine.addListener('LeaveChannel', data => {
    //   console.warn('LeaveChannel' + data);
    // });
    // this.engine.addListener('UserOffline', data => {
    //   console.warn('UserOffline' + data);
    // });
    await this.engine.enableWebSdkInteroperability(true); //打开与webSDK的互通
    await this.engine.setChannelProfile(0); //设置频道场景
    await this.engine.setClientRole(1); //设置为主播角色
    await this.engine.muteLocalAudioStream(true); //停止发送本地音频流
    // 加入频道
    await this.engine.joinChannel(data.token, data.channel, null, data.uid);
    //判断当前是否扬声器
    if (!(await this.engine.isSpeakerphoneEnabled())) {
      await this.engine.setEnableSpeakerphone(true); //切换到外放
    }
  } catch (e) {
    console.log(e);
  }
};

export const leaveTalkCall = async () => {
  if (this.engine) {
    await this.engine.leaveChannel();
  }
};

export default {onTalkCall, leaveTalkCall};
