<template>
	<RtcLayout :inviteData="inviteData" :authData="config" :connect="connect" :isConnected="isConnected"
		@connectRtc="connectRtc" :room="room!" />
</template>

<script setup lang="ts">
	import { useRoom } from '@/utils/open-im-rtc'
	import { IMSDK } from '@/utils/imCommon'
	import { InviteData, RtcInviteResults } from './data'
	import useUserStore from '@/store/modules/user'
	import RtcLayout from './RtcLayout/index.vue'
	import emitter from '@/utils/events'
	import { feedbackToast } from '@/utils/common'
	import { SessionType } from 'open-im-sdk-wasm'

	type RtcProps = {
		inviteData : InviteData
	}
	const props = defineProps<RtcProps>()

	const { t } = useI18n()
	const userStore = useUserStore()

	const connect = ref(false)
	const isConnected = ref(false)
	const config = reactive({
		serverUrl: '',
		token: '',
		connect: false,
		audio: true,
		video: props.inviteData.invitation?.mediaType === 'video',
	})
	const isRecv = computed(
		() => userStore.selfInfo.userID !== props.inviteData.invitation?.inviterUserID,
	)
	const isGroup = computed(
		() => props.inviteData.invitation?.sessionType !== SessionType.Single,
	)

	const room = useRoom({
		refConfig: config,
		onConnected: () => {
			isConnected.value = true
		},
		onDisconnected: () => {
			connect.value = false
			isConnected.value = false
			config.connect = false
		},
		onError: (error) => {
			feedbackToast({ message: t('rtc.joinFailed'), error })
			emitter.emit('CLOSE_RTC_MODAL')
		},
	})

	const connectRtc = (data ?: any) => {
		if (data) {
			config.serverUrl = data.liveURL
			config.token = data.token
			config.connect = true
		}
		connect.value = true
	}

	const tryInvite = async () => {
		if (props.inviteData.isJoin && props.inviteData.invitation?.roomID) {
			IMSDK.signalingGetTokenByRoomID<RtcInviteResults>(
				props.inviteData.invitation.roomID,
			)
				.then(({ data }) => {
					config.serverUrl = data.liveURL
					config.token = data.token
					config.connect = true
					if (isGroup.value) {
						connect.value = true
					}
				})
				.catch((error) => {
					feedbackToast({ message: t('rtc.joinFailed'), error })
					emitter.emit('CLOSE_RTC_MODAL')
				})
		}
		if (!isRecv.value) {
			const funcName = isGroup.value ? 'signalingInviteInGroup' : 'signalingInvite'
			try {
				const { data } = await IMSDK[funcName]<RtcInviteResults>({
					invitation: props.inviteData.invitation!,
				})
				config.serverUrl = data.liveURL
				config.token = data.token
				config.connect = true
				if (isGroup.value) {
					connect.value = true
				}
			} catch (error) {
				feedbackToast({ message: t('rtc.invitationFailed'), error })
				emitter.emit('CLOSE_RTC_MODAL')
			}
		}
	}

	onMounted(() => {
		tryInvite()
	})
</script>

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