import axios from "axios";

export class User
{
    username?: string;
    email?: string;
    password?: string;
    roles?: string[];
    initial?: boolean;

    static get(onSuccess: (users: User[]) => void)
    {
        axios.get(ApiConfig.getHttpBase() + '/users', {
            headers: {
                Authorization: "Bearer " + requireToken()
            }
        })
        .then((response) => {
            onSuccess(response.data);
        });
    }

    static create(user: UserCreation, onSuccess: () => void)
    {
        axios.post(ApiConfig.getHttpBase() + '/users', user, {
            headers: {
                Authorization: "Bearer " + requireToken()
            }
        })
        .then(() => {
            onSuccess();
        });
    }
}

export class UserCreation 
{
    firstname?: string;
    lastname?: string;
    email?: string;
    password?: string;
    username?: string;
    role: string = "USER";
}

export function hasAnyRole(user: User | undefined, requiredRoles: string[])
{
    if(user && user.roles != undefined)
    {
        const roles = user.roles;
        for(const role of roles)
        {
            if(requiredRoles.includes(role))
            {
                return true;
            }
        }
    }
    return false;
}