import React from 'react';
import ProviderFactory from './provider-factory';
const ProviderFactoryContext = /*#__PURE__*/React.createContext(new ProviderFactory());
export const ProviderFactoryProvider = ProviderFactoryContext.Provider;

// eslint-disable-next-line @atlaskit/volt-strict-mode/no-multiple-exports
export const useProviderFactory = () => React.useContext(ProviderFactoryContext);

// eslint-disable-next-line @atlaskit/volt-strict-mode/no-multiple-exports
export const useProvider = name => {
  const [provider, setProvider] = React.useState();
  const providerFactory = useProviderFactory();
  React.useEffect(() => {
    const providerHandler = (_, provider) => {
      setProvider(provider);
    };
    providerFactory.subscribe(name, providerHandler);
    return () => {
      providerFactory.unsubscribe(name, providerHandler);
    };
  }, [name, providerFactory]);
  return provider;
};

// eslint-disable-next-line @atlaskit/volt-strict-mode/no-multiple-exports
export const useProviderLayout = name => {
  const [provider, setProvider] = React.useState();
  const providerFactory = useProviderFactory();
  React.useLayoutEffect(() => {
    const providerHandler = (_, provider) => {
      setProvider(provider);
    };
    providerFactory.subscribe(name, providerHandler);
    return () => {
      providerFactory.unsubscribe(name, providerHandler);
    };
  }, [name, providerFactory]);
  return provider;
};