import { useAuthData } from "any-hooks/auth/useAuthData";
import { useAgoraClient } from "any-hooks/common/useAgoraClient";
import { watch } from "vue";
import { useInjector, useState } from "vue-vulcan";
import { useChannelStore } from "./useChannelStore";

/** 视频通讯中心，用于音视频聊天功能，可集成到会议中心模块（不推荐在页面组件中直接使用该hook模块） */
export function useVideoConference() {
  const { currentChannel, clearChannel }     = useInjector(useChannelStore);
  const { authData }                         = useInjector(useAuthData);
  const {
    joinChannelWithAgora, 
    leaveChannelWithAgora,     
    muteLocalStream, 
    unmuteLocalStream,
    muteRemoteStream,
    unmuteRemoteStream,
    streamList, 
    localPushurl,
  } = useAgoraClient();  

  /** 监听频道模块，频道被创建、更新后自动将agora的音视频通讯功能载入频道 */
  watch(currentChannel, channel => {    
    if(!channel) return;    
    join();
  })

  const join = () => {
    // setInChannel(true);
    joinChannelWithAgora(
      currentChannel.value.agora_token,
      currentChannel.value.channel_id,
      parseInt(authData.value.peer_id)
    )
  }

  /** 切换麦克风使用状态  */
  const [voiceMute, setVoiceMute] = useState(false);
  const switchLocalMicState = () => {
    if(!voiceMute.value) {
      setVoiceMute(true);
      muteLocalStream('audio');
    } else {
      setVoiceMute(false);
      unmuteLocalStream('audio');
    }
  }

  /** 切换视频与音频通讯 */
  const [mode, setMode] = useState<'video' | 'audio'>('video')
  const switchVideoOrAudio = () => {    
    streamList.value.forEach( stream => {
      if(mode.value === 'video'){
        muteRemoteStream(stream.uid, 'video');
        muteLocalStream('video')
      } else {
        unmuteRemoteStream(stream.uid, 'video');
        unmuteLocalStream('video');
      }
    })
    setMode(mode.value === 'video' ? 'audio' : 'video');
  }

  /** 停止音视频通讯功能 */
  const stopVideoConference = () => {
    setVoiceMute(false); //将麦克风、音视频状态重置
    setMode('video');
    clearChannel();
    leaveChannelWithAgora();    
  }

  return {
    streamList,
    localPushurl,
    voiceMute,
    mode,
    join,
    switchLocalMicState,
    switchVideoOrAudio,
    stopVideoConference
  }
}