import { useRef, useState } from 'react';

const useWebsocket = ({}) => {
  const ws = useRef();

  const [wsMessage, setWsMessage] = useState({});
  const [wsReadyState, setWsReadyState] = useState({ key: 0, value: '正在连接中' });

  const createWebSocket = (url) => {
    const stateArr = [
      { key: 0, value: '正在连接中' },
      { key: 1, value: '已经连接并且可以通讯' },
      { key: 2, value: '连接正在关闭' },
      { key: 3, value: '连接已关闭或者没有连接成功' },
    ];

    try {
      ws.current = new WebSocket(url);
      ws.current.onopen = () => {
        console.log('websocket open');
        setWsReadyState(stateArr[ws.current?.readyState ?? 0]);
      };
      ws.current.onclose = () => {
        console.log('websocket close');
        setWsReadyState(stateArr[ws.current?.readyState ?? 0]);
      };
      ws.current.onerror = () => {
        console.log('websocket error');
        setWsReadyState(stateArr[ws.current?.readyState ?? 0]);
      };
      ws.current.onmessage = (e) => {
        console.log('onmessage', e);
        setWsMessage(JSON.parse(e.data));
      };
    } catch (error) {
      console.log(error);
    }
  };

  const webSocketInit = (url) => {
    if (!ws.current || ws.current.readyState === 3) {
      createWebSocket(url);
    }
  };

  //  关闭 WebSocket
  const closeWebSocket = () => {
    ws.current?.close();
  };

  // 发送数据
  const sendMessage = (str) => {
    ws.current?.send(str);
  };

  //重连
  const reconnect = () => {
    try {
      closeWebSocket();
      ws.current = null;
      createWebSocket();
    } catch (e) {
      console.log(e);
    }
  };

  //   useEffect(() => {
  //     webSocketInit();

  //     return () => {
  //       ws.current?.close(1000);
  //     };
  //   }, [ws]);

  return {
    webSocketInit,
    wsMessage,
    setWsMessage,
    wsReadyState,
    reconnect,
    sendMessage,
    closeWebSocket,
  };
};

export default useWebsocket;
