import { useEffect } from 'react';
import { useServerUrl } from '@game/hooks/best-server';
import { GameServer, server } from '@game/network/server';

export function useConnect() {
  const { serverUrl } = useServerUrl();

  useEffect(() => {
    if (!serverUrl) {
      return;
    }

    const server = GameServer.connect(serverUrl);

    return () => {
      server.destroy();
    };
  }, [serverUrl]);

  return server;
}
