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

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

    async function fetch() {
        const { data } = await axios.get('VnUsers/acls');
        const acls = {};
        data.forEach((acl) => {
            acls[acl.model] = acls[acl.model] || {};
            acls[acl.model][acl.property] = acls[acl.model][acl.property] || {};
            acls[acl.model][acl.property][acl.accessType] = true;
        });

        state.setAcls(acls);
    }

    function hasAny(model, prop, accessType) {
        const acls = state.getAcls().value[model];
        if (acls) 
            return ['*', prop].some((key) => {
                const acl = acls[key];
                return acl && (acl['*'] || acl[accessType]);
            });
    }

    return {
        fetch,
        hasAny,
        state,
    };
}
