var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [0, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
import { a as Observable, b as Subject, c as from, d as scan, e as startWith, f as mergeMap, g as __extends, h as tryCatch, i as errorObject, j as Subscriber, k as map, l as tap } from "./chunk-7544ae3d.js";
import { a as Util, b as global$1 } from "./chunk-e405d082.js";
import { a as User, b as BaseService, c as PermissionsService } from "./chunk-e83794f9.js";
var RxUtil = /** @class */ (function () {
    function RxUtil() {
    }
    RxUtil.isObservable = function (e) { return e instanceof Observable; };
    RxUtil.log = function () { return console.log.bind(console); };
    return RxUtil;
}());
var action$ = new Subject, createStore = function (e, t) {
    if (t === void 0) { t = { timestamp: Util.getTimeStamp() }; }
    return action$.pipe(mergeMap(function (e) { return RxUtil.isObservable(e) ? e : from([e]); }), startWith(t), scan(e));
}, actionCreator = function (e) { return function () {
    var t = [];
    for (var _i = 0; _i < arguments.length; _i++) {
        t[_i] = arguments[_i];
    }
    var s = e.call.apply(e, [null].concat(t));
    return action$.next(s), RxUtil.isObservable(s.payload) && action$.next(s.payload), s;
}; };
function baseReducer(e, t) { switch (t.type) {
    case "CONFIG_LOADING": return Object.assign({}, e, { isLoading: !0, timestamp: Util.getTimeStamp() });
    case "CONFIG_LOADED":
        var s_1 = Object.assign({}, e, { isLoading: !1 });
        return Object.keys(t.payload).forEach(function (e) { s_1[e] = t.payload[e]; }), s_1.timestamp = Util.getTimeStamp(), s_1;
    case "ADD_CONFIG":
        var r_1 = Object.assign({}, e);
        return Object.keys(t.payload).forEach(function (e) { r_1[e] = t.payload[e]; }), r_1.timestamp = Util.getTimeStamp(), r_1;
    default: return e;
} }
var __window = "undefined" != typeof window && window, __self = "undefined" != typeof self && "undefined" != typeof WorkerGlobalScope && self instanceof WorkerGlobalScope && self, __global = void 0 !== global$1 && global$1, _root = __window || __global || __self;
function getCORSRequest() { if (_root.XMLHttpRequest)
    return new _root.XMLHttpRequest; if (_root.XDomainRequest)
    return new _root.XDomainRequest; throw new Error("CORS is not supported by your browser"); }
function getXMLHttpRequest() { if (_root.XMLHttpRequest)
    return new _root.XMLHttpRequest; var e = void 0; try {
    for (var t = ["Msxml2.XMLHTTP", "Microsoft.XMLHTTP", "Msxml2.XMLHTTP.4.0"], s = 0; s < 3; s++)
        try {
            if (e = t[s], new _root.ActiveXObject(e))
                break;
        }
        catch (e) { }
    return new _root.ActiveXObject(e);
}
catch (e) {
    throw new Error("XMLHttpRequest is not supported by your browser");
} }
function ajaxGet(e, t) { return void 0 === t && (t = null), new AjaxObservable({ method: "GET", url: e, headers: t }); }
function ajaxPost(e, t, s) { return new AjaxObservable({ method: "POST", url: e, body: t, headers: s }); }
function ajaxDelete(e, t) { return new AjaxObservable({ method: "DELETE", url: e, headers: t }); }
function ajaxPut(e, t, s) { return new AjaxObservable({ method: "PUT", url: e, body: t, headers: s }); }
function ajaxPatch(e, t, s) { return new AjaxObservable({ method: "PATCH", url: e, body: t, headers: s }); }
var mapResponse = map(function (e, t) { return e.response; });
function ajaxGetJSON(e, t) { return mapResponse(new AjaxObservable({ method: "GET", url: e, responseType: "json", headers: t })); }
var AjaxObservable = function (e) { function t(t) { var s = e.call(this) || this, r = { async: !0, createXHR: function () { return this.crossDomain ? getCORSRequest() : getXMLHttpRequest(); }, crossDomain: !0, withCredentials: !1, headers: {}, method: "GET", responseType: "json", timeout: 0 }; if ("string" == typeof t)
    r.url = t;
else
    for (var o in t)
        t.hasOwnProperty(o) && (r[o] = t[o]); return s.request = r, s; } var s; return __extends(t, e), t.prototype._subscribe = function (e) { return new AjaxSubscriber(e, this.request); }, t.create = ((s = function (e) { return new t(e); }).get = ajaxGet, s.post = ajaxPost, s.delete = ajaxDelete, s.put = ajaxPut, s.patch = ajaxPatch, s.getJSON = ajaxGetJSON, s), t; }(Observable), AjaxSubscriber = function (e) { function t(t, s) { var r = e.call(this, t) || this; r.request = s, r.done = !1; var o = s.headers = s.headers || {}; return s.crossDomain || o["X-Requested-With"] || (o["X-Requested-With"] = "XMLHttpRequest"), "Content-Type" in o || _root.FormData && s.body instanceof _root.FormData || void 0 === s.body || (o["Content-Type"] = "application/x-www-form-urlencoded; charset=UTF-8"), s.body = r.serializeBody(s.body, s.headers["Content-Type"]), r.send(), r; } return __extends(t, e), t.prototype.next = function (e) { this.done = !0; var t = this.xhr, s = this.request, r = this.destination, o = new AjaxResponse(e, t, s); r.next(o); }, t.prototype.send = function () { var e = this.request, t = this.request, s = t.user, r = t.method, o = t.url, n = t.async, a = t.password, i = t.headers, c = t.body, u = e.createXHR, p = tryCatch(u).call(e); if (p === errorObject)
    this.error(errorObject.e);
else {
    if (this.xhr = p, this.setupEvents(p, e), (s ? tryCatch(p.open).call(p, r, o, n, s, a) : tryCatch(p.open).call(p, r, o, n)) === errorObject)
        return this.error(errorObject.e), null;
    if (n && (p.timeout = e.timeout, p.responseType = e.responseType), "withCredentials" in p && (p.withCredentials = !!e.withCredentials), this.setHeaders(p, i), (c ? tryCatch(p.send).call(p, c) : tryCatch(p.send).call(p)) === errorObject)
        return this.error(errorObject.e), null;
} return p; }, t.prototype.serializeBody = function (e, t) { if (!e || "string" == typeof e)
    return e; if (_root.FormData && e instanceof _root.FormData)
    return e; if (t) {
    var s = t.indexOf(";");
    -1 !== s && (t = t.substring(0, s));
} switch (t) {
    case "application/x-www-form-urlencoded": return Object.keys(e).map(function (t) { return encodeURIComponent(t) + "=" + encodeURIComponent(e[t]); }).join("&");
    case "application/json": return JSON.stringify(e);
    default: return e;
} }, t.prototype.setHeaders = function (e, t) { for (var s in t)
    t.hasOwnProperty(s) && e.setRequestHeader(s, t[s]); }, t.prototype.setupEvents = function (e, t) { var s, r, o = t.progressSubscriber; function n(e) { var t = n, s = t.subscriber, r = t.progressSubscriber, o = t.request; r && r.error(e), s.error(new AjaxTimeoutError(this, o)); } (e.ontimeout = n, n.request = t, n.subscriber = this, n.progressSubscriber = o, e.upload && "withCredentials" in e) && (o && (s = function (e) { s.progressSubscriber.next(e); }, _root.XDomainRequest ? e.onprogress = s : e.upload.onprogress = s, s.progressSubscriber = o), r = function (e) { var t = r, s = t.progressSubscriber, o = t.subscriber, n = t.request; s && s.error(e), o.error(new AjaxError("ajax error", this, n)); }, e.onerror = r, r.request = t, r.subscriber = this, r.progressSubscriber = o); function a(e) { } function i(e) { var t = i, s = t.subscriber, r = t.progressSubscriber, o = t.request; if (4 === this.readyState) {
    var n = 1223 === this.status ? 204 : this.status, a = "text" === this.responseType ? this.response || this.responseText : this.response;
    0 === n && (n = a ? 200 : 0), n < 400 ? (r && r.complete(), s.next(e), s.complete()) : (r && r.error(e), s.error(new AjaxError("ajax error " + n, this, o)));
} } e.onreadystatechange = a, a.subscriber = this, a.progressSubscriber = o, a.request = t, e.onload = i, i.subscriber = this, i.progressSubscriber = o, i.request = t; }, t.prototype.unsubscribe = function () { var t = this.done, s = this.xhr; !t && s && 4 !== s.readyState && "function" == typeof s.abort && s.abort(), e.prototype.unsubscribe.call(this); }, t; }(Subscriber), AjaxResponse = function () { return function (e, t, s) { this.originalEvent = e, this.xhr = t, this.request = s, this.status = t.status, this.responseType = t.responseType || s.responseType, this.response = parseXhrResponse(this.responseType, t); }; }(), AjaxError = function (e) { function t(s, r, o) { var n = e.call(this, s) || this; return n.name = "AjaxError", n.message = s, n.xhr = r, n.request = o, n.status = r.status, n.responseType = r.responseType || o.responseType, n.response = parseXhrResponse(n.responseType, r), Object.setPrototypeOf(n, t.prototype), n; } return __extends(t, e), t; }(Error);
function parseXhrResponse(e, t) { switch (e) {
    case "json": return "response" in t ? t.responseType ? t.response : JSON.parse(t.response || t.responseText || "null") : JSON.parse(t.responseText || "null");
    case "xml": return t.responseXML;
    case "text":
    default: return "response" in t ? t.response : t.responseText;
} }
var AjaxTimeoutError = function (e) { function t(s, r) { var o = e.call(this, "ajax timeout", s, r) || this; return o.name = "AjaxTimeoutError", Object.setPrototypeOf(o, t.prototype), o; } return __extends(t, e), t; }(AjaxError), ajax = AjaxObservable.create;
var baseActions = { loadConfig: actionCreator(function (e) { return "string" == typeof e ? { type: "CONFIG_LOADING", payload: ajax(e).pipe(map(function (e) { return { type: "CONFIG_LOADED", payload: e.response }; })) } : { type: "CONFIG_LOADED", payload: e }; }), addConfig: actionCreator(function (e) { return { type: "ADD_CONFIG", payload: e }; }), setConfig: actionCreator(function (e, t) { var s = {}; return s[e] = t, { type: "ADD_CONFIG", payload: s }; }) };
function appReducer(e, t) { switch (t.type) {
    case "GITHUB_FOLLOWERS_LOADING": return Object.assign({}, e, { isLoading: !0 });
    case "GITHUB_FOLLOWERS_LOADED": return Object.assign({}, e, { isLoading: !1, users: t.payload });
    case "NAME_CHANGED": return Object.assign({}, e, { isLoading: !1, timestamp: Util.getTimeStamp(), name: t.payload });
    default: return e;
} }
var appActions = { changeName: actionCreator(function (e) { return ({ type: "NAME_CHANGED", payload: e }); }), loadGithubFollowers: actionCreator(function (e) { var t = "https://api.github.com/users/" + e.username + "/followers"; return { type: "GITHUB_FOLLOWERS_LOADING", payload: ajax(t).pipe(map(function (e) { return map(e.response, "login"); }), map(function (e) { return ({ type: "GITHUB_FOLLOWERS_LOADED", payload: e }); })) }; }) };
var __awaiter = function (e, t, s, r) { return new (s || (s = Promise))(function (o, n) { function a(e) { try {
    c(r.next(e));
}
catch (e) {
    n(e);
} } function i(e) { try {
    c(r.throw(e));
}
catch (e) {
    n(e);
} } function c(e) { e.done ? o(e.value) : new s(function (t) { t(e.value); }).then(a, i); } c((r = r.apply(e, t || [])).next()); }); };
var singleton = Symbol(), singletonEnforcer = Symbol();
var AppService = /** @class */ (function () {
    function AppService(e) {
        if (this.actions = appActions, this.baseUrl = "", this.loading = !0, this.authenticated = !1, this.errorMessage = "", e !== singletonEnforcer)
            throw new Error("Cannot construct singleton");
        this.base = BaseService.instance, this.permissions = PermissionsService.instance, this.config = this.base.config, this.user = new User("visitor"), this.initStores();
    }
    AppService.prototype.init = function (e, t) {
        if (t === void 0) { t = ""; }
        return __awaiter(this, void 0, void 0, function () { var _a, _b, _c, _d; return __generator(this, function (_e) {
            switch (_e.label) {
                case 0:
                    "" !== t && (this.baseUrl = t), this.appRoot = e;
                    return [4 /*yield*/, this.base.initApp(this.baseUrl + "/assets/config.json", !0, "_emaApp")];
                case 1:
                    _e.sent();
                    return [4 /*yield*/, this.permissions.loadRules(this.baseUrl + "/assets/permissions.json", !0, "rules")];
                case 2:
                    _e.sent(), this.baseUrl = t, this.base.translation.use(this.config.get("language")), this.data = {};
                    _a = this.data;
                    return [4 /*yield*/, Util.fetchJson(this.baseUrl + "/assets/collection-manifest.json")];
                case 3:
                    _a.manifest = _e.sent();
                    _b = this.data;
                    return [4 /*yield*/, Util.fetchJson(this.baseUrl + "/assets/data/mock-data.json")];
                case 4:
                    _b.mockData = _e.sent();
                    _c = this.data;
                    return [4 /*yield*/, Util.fetchJson(this.baseUrl + "/assets/data/mock-dwp.json")];
                case 5:
                    _c.dwpData = _e.sent();
                    _d = this.data;
                    return [4 /*yield*/, Util.fetchJson(this.baseUrl + "/assets/data/apiSwagger.json")];
                case 6: return [2 /*return*/, (_d.swaggerData = _e.sent(), this.collectionManifest = this.data.manifest, this.parseComponents(), this.initHistory(), window.document.location.hostname.match("localhost") && this.config.set("dev", !0), this.data)];
            }
        }); });
    };
    AppService.prototype.initStores = function () { return __awaiter(this, void 0, void 0, function () {
        var _this = this;
        return __generator(this, function (_a) {
            this.store$ = createStore(appReducer, {}), this.config$ = createStore(baseReducer), this.store$.pipe(tap(RxUtil.log())).subscribe(function (e) { }), this.config$.pipe().subscribe(function (e) { _this.base.config.add(e, !0); });
            return [2 /*return*/];
        });
    }); };
    AppService.prototype.test = function () { this.actions.changeName("Bob"), baseActions.loadConfig(this.baseUrl + "/assets/config.json"), baseActions.setConfig("foo", "bar"), console.log(this.user.roles), this.user.addRole("AUTHENTICATED"), this.user.addRole("DEVELOPER"), console.log(this.user.roles), this.user.removeRole("AUTHENTICATED"), console.log(this.user.roles), console.log(this.user.hasRole("DEVELOPER")), console.log(this.user.hasRole("AUTHENTICATED")), console.log(this.config.all()); };
    AppService.prototype.initHistory = function () { "undefined" != typeof window && window.history; };
    AppService.prototype.parseComponents = function () {
        var _this = this;
        var e = [];
        Util.copy(this.data.manifest.components).map(function (t) { var s = t.tag, r = !1; _this.config.get("componentsIgnorePatterns").forEach(function (e) { s.match(e) && (r = !0); }), r || e.push(t); }), this.components = e;
    };
    AppService.prototype.showFlashMessage = function (e, t, s) {
        if (s === void 0) { s = 2e3; }
        document.querySelector("ema-flash-message").show(e, t, s);
    };
    Object.defineProperty(AppService, "instance", {
        get: function () { return this[singleton] || (this[singleton] = new AppService(singletonEnforcer)), this[singleton]; },
        enumerable: true,
        configurable: true
    });
    return AppService;
}());
export { AppService as a };
