import { useStore } from "vuex";
import { watchEffect, watch, computed, nextTick } from 'vue'
import browser from "@/utils/browser";

let mini

export const useCurrentMini = () => mini

export const initialMini = (audioMuted) => {
  const store = useStore();
  const socket = computed(() => store.getters["rtc/socket"]);

  let isStop = false
  const stopUpdate = (cb) => {
    isStop = true
    cb()
    nextTick(() => isStop = false)
  }


  watch(socket, (news, olds, onCleatup) => {
    if (!socket.value) {
      return;
    }

    const signalActions = {
      openAudioCallback(isOpen) {
        stopUpdate(() => {
          audioMuted.value = !isOpen
          console.log('更改')
        })
      }
    }
    
    let stopMutedWatch
    const joinCallback = data => {
      console.log('join room')
      store.commit("rtc/setAvatar", browser.getURLParam("avatar"));
      stopMutedWatch && stopMutedWatch()
      console.log('进入监听')
      stopMutedWatch = watch(audioMuted, (audioMuted, oldAudioMuted) => {
        if (!isStop && audioMuted !== oldAudioMuted) {
          console.error(audioMuted, oldAudioMuted)
          socket.value.emit('signal', { type: 'openAudio', payload: !audioMuted })
          if (audioMuted) {
            console.log('静音请求')
          } else {
            console.log('开启声音请求')
          }
        }
      }, { immediate: true, flush: 'pre' })
    }
    const signalCallback = data => {
      if (data.type in signalActions) {
        signalActions[data.type](data.payload)
      }
    }

    socket.value.on("join", joinCallback)
    socket.value.on('signal', signalCallback)

    onCleatup(() => {
      stopMutedWatch && stopMutedWatch()
      socket.value.off('join', joinCallback)
      socket.value.on('signal', signalCallback)
    })
  }, { immediate: true })

  mini = {
    enterShare() {
      socket.value.emit('signal', { type: 'enterShareMode' })
    },
    leave() {
      socket.value.emit('signal', { type: 'onUnload' })
    }
  }

  return mini
}
