import { useEffect } from 'react';
import { useSocket } from 'components/easyUse';
import { getScreenId } from 'utils/screen';

export default function useRemoteControl(controlled: boolean, emitCallback, emitEvent, rootScreens: string) {
  const screenId = getScreenId();

  // 初始化socket
  const socket = useSocket(controlled);

  useEffect(() => {
    if (socket) {
      socket.on('message', (data) => {
        if (data.type === 'callback') {
          emitCallback(null, data.callbackData);
        } else {
          emitEvent(data);
        }
      });
    }
  }, [socket]);

  useEffect(() => {
    const rootScreensArr = JSON.parse(rootScreens) as number[];
    const enterRoom = async () => {
      rootScreensArr.map((d) => {
        socket?.get('/api/v3/remote/screen/enter', {
          id: d
        });
      });
    };

    if (socket) {
      enterRoom();
      socket.on('reconnect', () => {
        enterRoom();
      });
    }
  }, [socket, screenId, rootScreens]);

  return null;
}
