import {useEffect, useState} from 'react';
import {useParams} from 'react-router-dom';

import ClientContext from '@/context/client.js';
import LocalClient from '@/net/client/local.js';
import RemoteClient from '@/net/client/remote.js';
import {decode, encode} from '@/packets/index.js';
import Ui from '@/react-components/ui.jsx';

import styles from './play.module.css';

export default function Index() {
  const [client, setClient] = useState();
  const [disconnected, setDisconnected] = useState();
  const params = useParams();
  const [type, url] = params['*'].split('/');
  useEffect(() => {
    let Client;
    switch (type) {
      case 'local':
        Client = LocalClient;
        break;
      case 'remote':
        Client = RemoteClient;
        break;
    }
    class SilphiusClient extends Client {
      accept(packed) {
        super.accept(decode(packed));
      }
      transmit(packet) {
        super.transmit(encode(packet));
      }
    }
    const client = new SilphiusClient();
    async function connect() {
      await client.connect(url);
      setClient(client);
    }
    connect();
    return () => {
      client.disconnect();
    };
  }, [type, url]);
  useEffect(() => {
    if (!client) {
      return;
    }
    function onConnectionAborted() {
      setDisconnected(true);
    }
    client.addPacketListener('ConnectionAborted', onConnectionAborted);
    return () => {
      client.removePacketListener('ConnectionAborted', onConnectionAborted);
    };
  }, [client]);
  return (
    <div className={styles.play}>
      {client && (
        <ClientContext.Provider value={client}>
          <Ui disconnected={disconnected} />
        </ClientContext.Provider>
      )}
    </div>
  );
}
