import Result from 'client/Components/Result';
import Spinner from 'client/Components/Spinner';
import Button from 'client/Elements/Button';
import { CenterContent } from 'client/Elements/Wrapper';
import { useStores } from 'client/hooks/useStores';
import { useAsync } from 'react-async-hook';

export default (Component, storesList) => () => {
  const stores = useStores();
  const initStores = async function () {
    for (const storeName of storesList) await stores[storeName].init();
  };

  const res = useAsync(initStores, [storesList]);

  if (res.loading) {
    return (
      <CenterContent>
        <Spinner />
      </CenterContent>
    );
  }

  if (res.error) {
    const ServerError = Result[500];
    const RetryButton = (
      <Button text="Попробовать еще раз" action={() => res.execute()}></Button>
    );
    return <ServerError extra={[RetryButton]} />;
  }

  return <Component />;
};
