import React from 'react';
// import { Navigate } from 'react-router-dom';
import useUserModel from '@/store/user';
import Predicate from './Predicate';

function Fallback (props) {
  const { state, loading } = props;
  const [_, { getCurrentUser }] = useUserModel();

  React.useEffect(() => {
    if (state == 'loading') {
      getCurrentUser();
    }
  }, [state]);

  // return <Navigate replace to="/login" />;
  //   window.location.href = getLoginPage();
  return state == 'loading' ? loading : null;
}

export default function RequireLogin (props) {
  const { loading } = props;
  const [user] = useUserModel();

  const calc = React.useCallback((user) => {
    if (!user?.user) {
      return 'loading';
    }

    return user.isLogin || false;
  }, []);

  return (
    <Predicate fallback={<Fallback loading={loading} />} value={user} calc={calc}>
      {props.children}
    </Predicate>
  )
}
