<script setup lang='ts'>
import type { type_dyaw_xlfw_zxhd, type_dyaw_xlfw_zxhd_log, type_archives_item } from '~/types';
import user from '~/store/user';
import type { TSocketRes } from '~/utils/ws';
import { CHAT_STATUS, CHAT_OPERATION } from '~/types';

// ==========
// chat audio/video
// ==========

let RtcDialogRef = $ref<typeof import("~/components/rtc-dialog/index.vue")['default']>()

let ws2: WebSocket
onMounted(() => {
  ws2 = createSocket(
    { teacher: user.user_id, student: '*' },
    {
      message(socketRes: TSocketRes<type_dyaw_xlfw_zxhd_log & { operate: CHAT_OPERATION }>) {
        console.info('enter message', socketRes);
        if (socketRes.from_client_name!.endsWith('student')) {
          // infoList.push(socketRes.content)
          if (socketRes.content!.dxzl_tea_user_id === user.user_id) {
            console.info('start publisher ')
            RtcDialogRef!.publisher(socketRes.content)
          }
        }
      },
      reload() {
        location.reload()
      }
    }
  )
  RtcDialogRef!.init(ws2)
})

onBeforeUnmount(() => {
  ws2?.close()
})

function openRtcDialog(dyaw_xlfw_zxhd: type_dyaw_xlfw_zxhd, type: 'audio' | 'video') {
  if (!ws2 || ws2.readyState !== 1) {
    ws2 = createSocket(
      { teacher: user.user_id, student: '*' },
      {
        message(socketRes: TSocketRes<type_dyaw_xlfw_zxhd_log & { operate: CHAT_OPERATION }>) {
          console.info('enter message', socketRes);
          if (socketRes.from_client_name.endsWith('student')) {
            // infoList.push(socketRes.content)
            if (socketRes.content.dxzl_tea_user_id === user.user_id) {
              console.info('start publisher ')
              RtcDialogRef!.publisher(socketRes.content)
            }
          }
        }
      }
    )
  }
  RtcDialogRef!.open(dyaw_xlfw_zxhd, type)
}


const updateFnList = $ref<Function[]>([])
function emitUpdateInfo(info: type_dyaw_xlfw_zxhd_log, isUpdate?: boolean) {
  updateFnList.forEach(fn => fn(info, isUpdate))
}
</script>

<template>
  <RouterView @openRtcDialog="openRtcDialog" :update-fn-list="updateFnList"></RouterView>
  <rtc-dialog ref="RtcDialogRef" @update-info="emitUpdateInfo"></rtc-dialog>
</template>
