var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
import { Util } from '../util/util';
import { HttpService } from '../http/http-service';
const singleton = Symbol();
const singletonEnforcer = Symbol();
export class PermissionsService {
    constructor(enforcer) {
        this._roles = {
            ANONYMOUS: [{ actions: 'read', subject: 'all' }]
        };
        if (enforcer !== singletonEnforcer) {
            throw new Error('Cannot construct singleton');
        }
        this._type = 'PermissionsService';
        this._http = HttpService.instance;
        this._rules = this._roles.ANONYMOUS;
    }
    static get instance() {
        if (!this[singleton]) {
            this[singleton] = new PermissionsService(singletonEnforcer);
        }
        return this[singleton];
    }
    loadRules(url, replace = true, pluck = undefined) {
        return __awaiter(this, void 0, void 0, function* () {
            let data = yield this._http.get(url);
            if (pluck) {
                data = data[pluck];
            }
            this.addRules(data, replace);
        });
    }
    addRules(rules, replace = false) {
        if (!replace) {
            this.rules = [...this.rules, ...rules];
        }
        else {
            this.rules = rules;
        }
        if (Util.isBrowser()) {
            dispatchEvent(new CustomEvent('permissionsRulesChange', { detail: { rules: this.rules } }));
        }
        // this.registerPermissionComponents();
    }
    registerPermissionComponents(componentElements) {
        let components = componentElements || Array.from(document.getElementsByTagName('ema-permission'));
        components.forEach((comp) => {
            comp['setPermissionService'](this);
            // comp['setRules'](this.rules);
        });
    }
    get rules() {
        return this._rules;
    }
    get roles() {
        return this._roles;
    }
    get user() {
        return this._user;
    }
    set user(user) {
        this._user = user;
    }
    set rules(rules) {
        this._rules = rules;
        if (Util.isBrowser()) {
            dispatchEvent(new CustomEvent('permissionsRulesChange', { detail: { rules: this._rules } }));
        }
    }
    get type() {
        return this._type;
    }
    set type(value) {
        this._type = value;
    }
}
//# sourceMappingURL=permissions-service.js.map