import { useAppStore } from '../store/modules/app';
import { getApp } from './userApp';
import { useRoom } from './useRoom';
import { useRtcStore } from '/@/store/modules/rtc';

const io = (window as any).io as SocketIOClientStatic;
let socket: SocketIOClient.Socket;

interface ReturnUseSocketType {
  createSocket: Fn;
  closeSocket: Fn;
  socket: SocketIOClient.Socket;
}

export function createSocket() {
  const rtcStore = useRtcStore();
  // console.log('rtcStore', rtcStore)
  const address = import.meta.env.VITE_APP_SOCKET_URL;
  socket = io(address, {
    path: '/ws-sync',
    transports: ['websocket'],
  });
  rtcStore.setSocket(socket);
  return socket;
}

async function closeSocket() {
  const { leaveRoom, createNewURLEntry } = useRoom();
  const rtcStore = useRtcStore();
  const appStore = useAppStore();
  await getApp().Connect.follow.exit();
  await leaveRoom();
  appStore.setIsTourMode(true);
  if (rtcStore.isLeader) {
    socket.emit('action', { type: 'leader-dismiss' });
  }
  rtcStore.clearMemberList();
  setTimeout(() => {
    createNewURLEntry({
      vruserId: '',
      isTour: 1,
      name: '',
      role: '',
      roomId: rtcStore.roomId,
      avatar: '',
    });
    // location.reload();
  }, 100);
}

export function useSocket(): ReturnUseSocketType {
  return {
    socket,
    closeSocket,
    createSocket,
  };
}
