import React from 'react';
import Error from '@/components/Error';
import useUserModel from '@/store/user';
import Predicate from './Predicate';

export default function Auth(props) {
  const { code, loading } = props;
  const [user] = useUserModel();
  const permissions = user?.permissions || [];
  
  const fallback = React.useCallback(({ state }) => {
    if (state == 'loading') {
        return loading;
    }

    return <Error />; 
  }, [loading]);

  const calc = React.useCallback((roles) => {
    if (!roles || roles.length == 0) {
        return 'loading';
    }

    return roles.indexOf(code) > -1;
  }, [code]);

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