
// import react
import { Auth as AuthEmitter } from '@moonup/node';
import React, { useState, useEffect } from 'react';

// socket context
import useSocket from '../hooks/useSocket';
import AuthContext from '../contexts/Auth';

/**
 * nft auth provider
 *
 * @param props 
 */
const MoonAuthProvider = (props = {}) => {
  // socket
  const socket = useSocket();

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

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

  // load account
  useEffect(() => {
    // set acid
    if (typeof localStorage === 'undefined') return;
    
    // set item
    localStorage.setItem('acid', emitter?.state?.account);
  }, [emitter?.state?.account]);

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

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

    // add listener
    emitter.on('user', onUpdated);
    emitter.on('loading', onUpdated);
    emitter.on('updated', onUpdated);
    emitter.on('account', onUpdated);

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

  // state
  const emitterState = emitter?.state;

  // to window
  if (typeof window !== 'undefined') window.MoonAuth = emitterState;

  // context
  return (
    <AuthContext.Provider value={ emitterState }>
      { props.children }
    </AuthContext.Provider>
  );
};

/**
 * NFT Wrapper
 * 
 * @param props 
 * @returns 
 */
const MoonAuthWrap = (props = {}) => {

  // return jsx
  return (
    <MoonAuthProvider { ...props } />
  );
};

// export default
export default MoonAuthWrap;