import { useChatStore } from "@/stores";

// WebSocket
export const useWebSocketStore = defineStore("websocket", () => {
  const websocket = ref<WebSocket>();
  const connected = ref(false);
  const chatStore = useChatStore();

  const { onlineCount } = storeToRefs(chatStore);

  const onmessage = (e: MessageEvent) => {
    const data = JSON.parse(e.data);
    switch (data.type) {
      case "count":
        onlineCount.value = data.online_count;
        break;
      case "asr_result":
        chatStore.addMessageToHistory(data.result);
    }
  };

  const send = (data: string) => {
    if (websocket.value && websocket.value.readyState === WebSocket.OPEN)
      websocket.value?.send(data);
  };
  const close = () => {
    websocket.value?.close();
  };

  const connect = () => {
    const url = "ws://127.0.0.1:8000/websocket";
    websocket.value = new WebSocket(url);

    websocket.value.onopen = () => {
      connected.value = true;

      let pingIntervalId: NodeJS.Timeout | undefined;

      if (pingIntervalId)
        clearInterval(pingIntervalId);
      pingIntervalId = setInterval(() => send("ping"), 30 * 1000);

      if (websocket.value) {
        websocket.value.onmessage = onmessage;

        websocket.value.onerror = (e: Event) => {
          console.error(`WebSocket错误:${(e as ErrorEvent).message}`);
        };
        websocket.value.onclose = () => {
          connected.value = false;
          setTimeout(() => {
            connect(); // 尝试重新连接
          }, 1000); // 1秒后重试连接
        };
      }
    };
  };

  return {
    websocket,
    connected,
    send,
    close,
    connect,
  };
});
