
// socketio client
import { Socket as SocketEmitter } from '@moonup/node';
import React, { useEffect, useState } from 'react';

// socket context
import useId from '../hooks/useId';
import Context from '../contexts/Socket';

// global this
const globalThis = typeof window !== 'undefined' ? window : global;

// socket context
const MoonSocketProvider = (props = {}) => {
  // use id
  const nanoid = useId();

  // session id
  const [ssid] = useState(() => {
    // set state
    return (globalThis.localStorage) && globalThis.localStorage.getItem('ssid') || `${nanoid()}`;
  });

  // create emitter
  const [emitter, setEmitter] = useState(() => {
    // return emitter
    return globalThis.socketEmitter || new SocketEmitter({
      url : props.url,
      ssid,
    });
  });

  // use effect
  useEffect(() => {
    // do props
    emitter.props({
      url : props.url,
      ssid,
    });
  }, [props]);

  // use effect
  useEffect(() => {
    // check emitter
    if (!emitter) return;

    // set item
    if (globalThis.localStorage) globalThis.localStorage.setItem('ssid', ssid);
  }, [emitter]);

  // to window
  globalThis.MoonSocket = emitter?.state;

  // return jsx
  return (
    <Context.Provider value={ emitter?.state }>
      { props.children }
    </Context.Provider>
  );
};

// export default
export default MoonSocketProvider;