import { useState } from './useState';
import axios from 'axios';

export function useRole() {
    const state = useState();

    async function fetch() {
        const { data } = await axios.get('VnUsers/acl');
        const roles = data.roles.map((userRoles) => userRoles.role.name);

        const userData = {
            id: data.user.id,
            name: data.user.name,
            nickname: data.user.nickname,
            lang: data.user.lang || 'es',
        };
        state.setUser(userData);
        state.setRoles(roles);
    }

    function hasAny(roles) {
        const roleStore = state.getRoles();

        for (const role of roles) {
            if (roleStore.value.indexOf(role) !== -1) return true;
        }

        return false;
    }

    return {
        fetch,
        hasAny,
        state,
    };
}
