import { Navigate, useLocation } from 'react-router-dom';
import useAuth from '../Auth/useAuth';
import { useSelector } from 'react-redux';

export default function RequireAuth({ children }) {

    let auth = useAuth();
    let location = useLocation();
    let { authorities } = auth.getRole();
    authorities = authorities ? authorities.map( e => e.toUpperCase()) : [] ;

    if (!auth.isLogged()) {
        if( authorities.includes("CANDIDATO")){
            console.log("redirigir candidato")
            return <Navigate to="/logincd" state={{ from: location }} replace />;
        }else{
            console.log("redirigir recluter")
            return <Navigate to="/login" state={{ from: location }} replace />;
        }
    }

    return children;
}

export function RequireToken({ children }) {

    let token = useSelector((state) => state.token.token)
    let location = useLocation();
    // let { authorities } = auth.getRole();
    // authorities = authorities ? authorities.map( e => e.toUpperCase()) : [] ;

    if (!token) {
      console.log('falta authorizacion user')
      return <Navigate to="/logincd" state={{ from: location }} replace />;
    }

    return children;
}
