<template>
  <rtc-modal v-if="showRtcModal" :inviteData="inviteData"></rtc-modal>
</template>

<script setup lang="ts">
import { InviteData, ParticipantInfo } from '@/pages/rtc/data'
import rtcModal from '@/pages/rtc/index.vue'
import emitter from '@/utils/events'
import { IMSDK } from '@/utils/imCommon'
import { CbEvents } from 'open-im-sdk-wasm'
import type { RtcInvite, WSEvent } from 'open-im-sdk-wasm/lib/types/entity'

const showRtcModal = ref(false)
const inviteData = reactive<InviteData>({})

const recvInvitationHandler = ({
  data,
}: WSEvent<{ participant: ParticipantInfo; invitation: RtcInvite }>) => {
  inviteData.invitation = data.invitation
  inviteData.participant = data.participant
  showRtcModal.value = true
}

const openRtcModalHandler = (data: InviteData) => {
  if (showRtcModal.value) return
  inviteData.invitation = data.invitation
  inviteData.participant = data.participant
  inviteData.isJoin = data.isJoin
  showRtcModal.value = true
}

const closeRtcModalHandler = () => {
  showRtcModal.value = false
}

onMounted(() => {
  IMSDK.on(CbEvents.OnReceiveNewInvitation, recvInvitationHandler)
  emitter.on('OPEN_RTC_MODAL', openRtcModalHandler)
  emitter.on('CLOSE_RTC_MODAL', closeRtcModalHandler)
})

onUnmounted(() => {
  IMSDK.off(CbEvents.OnReceiveNewInvitation, recvInvitationHandler)
  emitter.off('OPEN_RTC_MODAL', openRtcModalHandler)
  emitter.off('CLOSE_RTC_MODAL', closeRtcModalHandler)
})
</script>

<style lang="scss" scoped></style>
