import React from "react";
import globals from "../globals";
import { apiClient } from "../utils/httpClients";
import propTypes from "prop-types";

export default class AuthenticationGuard extends React.Component {
    constructor(props) {
        super(props);
    }
    static contextType = globals;

    async componentDidMount() {
        let userDataResponse = await apiClient.get("/user");
        if (userDataResponse.status === 200) {
            this.context.update({ user: userDataResponse.data });
        } else if (userDataResponse.status == 401) {
            this.context.navigate("/signup", { replace: true });
        }
        if (this.context.user && this.context.user.accessLevel < this.props.accessLevel) {
            this.context.navigate("/", { replace: true });
        }
    }

    render() {
        if (this.context.user) {
            return this.props.children;
        } else {
            return null;
        }
    }
}

AuthenticationGuard.defaultProps = {
    accessLevel: 0
};

AuthenticationGuard.propTypes = {
    accessLevel: propTypes.number,
    children: propTypes.any
};