import React, { useState, useEffect } from "react";
import PropTypes from "prop-types";
import { Redirect } from "react-router-dom";
import { useServerApi } from "../api";
import CheckingServerHealth from "../availability/components/CheckingServerHealth";

const ServerAvailabilityProvider = ({ children }) => {
  const [ok, setOk] = useState(null);
  const { checkHealth } = useServerApi();

  useEffect(() => {
    checkHealth({
      onCompleted: () => setOk(true),
      onError: () => setOk(false)
    });
  }, [checkHealth]);

  if (ok === null) return <CheckingServerHealth />;
  if (ok === false) return <Redirect to="/server-not-available" />;
  return <>{children}</>;
};

ServerAvailabilityProvider.propTypes = {
  children: PropTypes.node
};

export default ServerAvailabilityProvider;
