import { watch } from "vue";
import { useContacts } from "any-hooks/contacts/useContacts";
import { UserData } from "any-hooks/types/user";
import { useInjector, useState } from "vue-vulcan";
import { useCallCenter } from "./useCallCenter";
import { useChannelStore } from "./useChannelStore";
import { useVideoConference } from "./useVideoConference";

interface MeetingMember {
  id: string;
  user?: UserData;
  self?: boolean;
  video?: {
    loaded?: boolean,
    url?: string 
  };
  chat?: {
    loaded: boolean
  }
}

/** 会议中心功能, 该功能在呼叫功能生效后使用，此模块会将其他即时交互模块集中到一起，如：音视频通讯模块、文本聊天模块等(目前只有音视频通讯) */
export function useMeetingCenter() {  
  const {hangup, myCallState}   = useInjector(useCallCenter);
  const {streamList, localPushurl, voiceMute, mode, join, stopVideoConference, switchLocalMicState, switchVideoOrAudio} = useInjector(useVideoConference);

  /** 离开会议(分两步：1.挂断当前呼叫， 2.停止音视频功能) */
  const leave = () => {
    hangup('leave');
    stopVideoConference();
  }  

  /** 监听频道成员信息 */
  const { channelMembers } = useInjector(useChannelStore);
  const [meetingMembers, setMembers] = useState<MeetingMember[]>([]);
  const { getContactById } = useInjector(useContacts);
  watch(channelMembers, cmembers => {
    const arr = cmembers.map( id => {
      const user = getContactById(id, 'uid'); 
      return {
        id,
        user,
        video: {
          loaded: false
        }
      }
    })
    setMembers(arr);
  })

  /** 监听视频流列表，长度为1时，自动退出频道  （目前直接用agora stream替代）*/
  watch(streamList, (current, last) => {    
    if(myCallState.value === 'idle') return;
    if(current.length > last.length) {      
      return
    };
    if(current.length === 0) {      
      setTimeout(leave, 2000)
    }
  }) 
  return {
    streamList,
    meetingMembers,
    localPushurl,
    voiceMute,
    mode,
    join,
    leave,
    switchLocalMicState,
    switchVideoOrAudio
  }
}