export default class PermissionManager {

    constructor(store, eventBus) {

        this.store = store;
        this.eventBus = eventBus;

        this.permissions = new Set();

        // Auto-update when store changes
        this.eventBus.on('store:changed:auth.user', () => {
            this.reload();
        });
    }

    reload() {

        const perms = this.store.get("auth.user.permissions") || [];

        this.permissions = new Set(perms);

    }

    /* -----------------------------------------
       CHECK PERMISSIONS
    ----------------------------------------- */

    can(permission) {
        return this.permissions.has(permission);
    }

    cannot(permission) {
        return !this.can(permission);
    }

    must(permission) {

        if (this.cannot(permission)) {
            throw new Error(`Permission denied: ${permission}`);
        }

    }

}
