import {useEffect, useState} from 'react';
import {Outlet, 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 styles from './play.module.css';

export default function Index() {
  const [client, setClient] = 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]);
  return (
    <div className={styles.play}>
      {client && (
        <ClientContext.Provider value={client}>
          <Outlet />
        </ClientContext.Provider>
      )}
    </div>
  );
}
