import { computed, watch } from "vue";
import { useInjector, useRequest, useState } from "vue-vulcan";
import { useNetSocketStore } from "./useNetSocketStore";

interface ChannelData {
  channel_id: string;
  agora_token: string;  
}

/** 频道中心功能，可以创建频道，并保存当前频道的信息，供呼叫中心、会议中心使用（目前同一时间仅允许存在一个频道） */
export function useChannelStore() {
  const [currentChannel, setChannel]   = useState<ChannelData>(null);
  const [isInChannel, setInChannel]    = useState(false);
  const [channelMembers, setMembers]   = useState<string[]>([]);
  const [channelInfo, request]         = useRequest<ChannelData>('/getAgoraToken', {auto: false});
  const { currentMsg }                 = useInjector(useNetSocketStore);  
  

  /* 创建新的频道(如果已存在一个频道则不调用创建接口，直接返回一个promise) */
  const createChannel = () => { 
    if(!currentChannel.value) return request();    
    updateMembers();
    return new Promise<ChannelData>(resolve => resolve(channelInfo.value));
  }  

  const getTokenByChannel = (cid: string) => {   
    return request({channel_id: cid}).then(_ => updateMembers());
  }   

  const [members, requestMembers] = useRequest<any[]>('/getChannelUser', {auto: false})
  const isEmpty = computed( () => members.value && members.value.length < 2); //频道剩余不到1人时，表示为空
  const updateMembers = () => {
    if(!currentChannel.value?.channel_id) return new Promise(resolve => resolve(null));
    return requestMembers({channel_id: currentChannel.value.channel_id})
  }  

  const clearChannel = () => {
    setChannel(null);
    setInChannel(false);
    setMembers([]);
  }

  watch(channelInfo, val => {    
    setChannel(val);    
    updateMembers();
  })

  //监听频道下的成员实时信息
  watch(currentMsg, msg => {
    if(msg.msgMainFlag !== 'ChannelChat') return;
    switch(msg.msgSubFlag) {
      case 'Hangup':
        updateMembers();
      break;
    }
  })


  return {
    currentChannel,
    channelMembers,
    isEmpty,
    isInChannel,
    getTokenByChannel,
    createChannel,
    setInChannel,
    updateMembers,        
    clearChannel
  }
}