
// socketio client
import useAuth from '../hooks/useAuth';
import useSocket from '../hooks/useSocket';
import DesktopContext from '../contexts/Desktop';
import { Desktop as DesktopEmitter } from '@moonup/node';
import React, { useEffect, useState } from 'react';

// socket context
const MoonDesktopProvider = (props = {}) => {
  // socket
  const auth = useAuth();
  const socket = useSocket();

  // updated
  const [updated, setUpdated] = useState(() => {
    // return date
    return new Date();
  });

  // create emitter
  const [emitter, setEmitter] = useState(() => {
    // return emitter
    return (typeof window !== 'undefined' ? window.desktopEmitter : null) || new DesktopEmitter({
      auth,
      socket,
    });
  });

  // use effect
  useEffect(() => {
    // do props
    emitter.props({
      auth,
      socket,
    });
  }, [auth?.account]);

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

    // create listener
    const onUpdated = () => setUpdated(new Date());

    // add listener
    emitter.on('updated', onUpdated);
    emitter.on('loading', onUpdated);
    emitter.on('desktop', onUpdated);
    emitter.on('activeTask', onUpdated);

    // return
    return () => {
      // return done
      emitter.removeListener('updated', onUpdated);
      emitter.removeListener('loading', onUpdated);
      emitter.removeListener('desktop', onUpdated);
      emitter.removeListener('activeTask', onUpdated);
    };
  }, [emitter]);

  // nft desktops
  if (typeof window !== 'undefined') window.MoonDesktop = emitter?.state;

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

// export default
export default MoonDesktopProvider;