"use strict";
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());
    });
};
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 };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
var storage_1 = require("../../util/storage");
var util_1 = require("../../util/util");
var base_api_1 = require("../../base/base-api");
var drupal_api_1 = require("./drupal-api");
var config_service_1 = require("../../config/config-service");
var Drupal = /** @class */ (function () {
    function Drupal(config, apiService) {
        if (config === void 0) { config = undefined; }
        if (apiService === void 0) { apiService = undefined; }
        this.cache = false;
        this.defaultAuthHeader = 'Basic c2VydmljZXM6OSs0djJGdm0zMi84Ymtl';
        this.defaultUser = 'services';
        this.model = {
            entities: {},
            collections: {},
            views: {},
            menus: {},
            books: {},
            siteParams: {},
            nodes: {},
        };
        this.restoreLocalModel = storage_1.Storage.restoreLocalModel;
        this.routes = {};
        this.sites = {};
        this.saveLocalModel = storage_1.Storage.saveLocalModel;
        this.user = {};
        this.version = 'drupal-8';
        this.config = config_service_1.ConfigService.instance;
        this.api = new base_api_1.BaseApi(); // todo: deprecate
        this.api.corsMode = 'cors'; // no-cors, cors, *same-origin (default)
        this.jsonApi = new drupal_api_1.DrupalApi();
        this.jsonApi.corsMode = 'cors';
        if (apiService) {
            // add Angular Observable api
            this.api = apiService;
        }
        this.model.entities = this.jsonApi.entities;
        this.model.collections = this.jsonApi.collections;
        this.model.nodes = this.jsonApi.nodes;
        this.model.views = this.jsonApi.views;
        if (config) {
            this.config.add(config);
        }
    }
    Drupal.prototype.init = function (options) {
        this.options = options;
        if (options.version) {
            this.version = options.version;
        }
        this.domain = options.domain;
        this.static = options.static || false;
        this.cache = options.cache || false;
        this.standalone = options.standalone || false;
        this.base_path = options.base_path || '/';
        this.protocol = options.protocol || 'http:';
        this.sites[this.domain] = {};
        this.file_directory_path = options.file_directory_path || 'sites/default/files';
        this.file_directory_path = this.baseUrl + this.file_directory_path;
        this.initApi(options);
        var promises = [];
        if (util_1.Util.isOnline() && !this.static) {
            // online
            // promises.push(jDrupal.connect());
            promises.push(this.getParams());
            promises.push(this.getLocalStorageCredentials());
            promises.push(this.jsonApi.getResourcesIndex(options.api.path_prefix, this.config.get('language')));
            promises.push(new Promise(function (resolve) {
                resolve();
            }));
            return Promise.all(promises);
        }
        else {
            // fixme: todo: offline or static
            // const self = this;
            return new Promise(function (resolve) {
                // self.restoreLocalModel(self.domain)
                // self.getLocalStorageCredentials().then(() => {
                resolve();
                // })
            });
        }
    };
    Drupal.prototype.initApi = function (options) {
        this.baseUrl = options.api.host = this.protocol + '//' + this.domain + this.base_path;
        this.api.init(options.api);
        this.jsonApi.init(options.api);
        this.jsonApi.cache = this.cache;
        // todo:
        if (this.config.get('drupal')['hasLanguages'] && this.config.get('language')) {
            //     this.api.baseUrl += this.config.getVar('language') + '/';
            //     this.jsonApi.baseUrl += this.config.getVar('language') + '/';
        }
        if (typeof window !== 'undefined') {
            // drupal-8
            window['drupalSettings'] = window['drupalSettings'] || {};
            // drupal-7
            if (window['Drupal']) {
                if (window['Drupal'].url && window['Drupal'].url.isLocal()) {
                    this.isLocal = true;
                }
                else {
                    this.isLocal = false;
                }
            }
            window['Drupal'] = window['Drupal'] || {};
            window['Drupal'].app_server_model = this.model;
            window['Drupal'].settings = window['Drupal'].settings || {};
            window['Drupal'].settings.baseUrl = this.baseUrl;
        }
        if (this.version === 'drupal-8') {
            if (!util_1.Util.getGlobal()['jDrupal']) {
                this.initJDrupal();
            }
            jDrupal = util_1.Util.getGlobal()['jDrupal'];
            jDrupal.config('sitePath', this.options.protocol + '//' + this.options.domain);
            // if (typeof window !== 'undefined' && !window['jDrupal']) {
            //     console.error('ERROR: jDrupal is not defined in the global namespace.');
            //     return;
            // }
            // this.jDrupal = jDrupal;
            // jDrupal.config('sitePath', this.options.protocol + '//' + this.options.domain);
        }
        if ('withCredentials' in new XMLHttpRequest) {
            this.cors = true;
        }
    };
    ;
    Drupal.prototype.login = function (username, password) {
        var self = this;
        return new Promise(function (resolve) {
            jDrupal.userLogin(username, password).then(function () {
                self.user = jDrupal.currentUser();
                self.api.setCredentials(jDrupal.settings, 'drupal:authUser:' + self.domain);
                self.authenticated = true;
                resolve();
            });
        });
    };
    Drupal.prototype.logout = function () {
        var self = this;
        return new Promise(function (resolve) {
            // fixme: drupal permission denied;
            //jDrupal.userLogout().then(function() {
            self.jsonApi.logout('drupal:authUser:' + self.domain);
            self.authenticated = false;
            console.log('logged out');
            resolve();
        });
    };
    Drupal.prototype.getParams = function () {
        var self = this;
        return new Promise(function (resolve) {
            var url = 'index.php/rest/params';
            if (self.version === 'drupal-7') {
                url = '?q=rest/app_params.json';
            }
            self.jsonApi.get(url, { _format: 'json' }).then(function (result) {
                self.model.siteParams = self.siteParams = result;
                resolve(result);
            });
        });
    };
    ;
    // todo: get by name
    Drupal.prototype.getView = function (viewEntity, params) {
        var _this = this;
        if (params === void 0) { params = undefined; }
        return new Promise(function (resolve, reject) {
            var entity = viewEntity;
            _this.api.get(entity.attributes.display.rest_export_1.display_options.path, params).then(function (res) {
                _this.model.views[entity.attributes.id] = res;
                resolve();
            });
        });
    };
    Drupal.prototype.getAppNode = function (uuid) {
        var _this = this;
        return new Promise(function (resolve) {
            _this.jsonApi.getNode(uuid, 'app').then(function (node) {
                var dataPromises = [];
                var attributes = node.data.attributes;
                if (attributes.field_cache === true) {
                    _this.jsonApi.cache = attributes.field_cache;
                }
                // fixme: all collections
                if (attributes.field_preload_collections) {
                    dataPromises.push(_this.jsonApi.getAllCollections(true));
                }
                // getVar entity reference fields
                Object.keys(_this.model.entities).forEach(function (k) {
                    var entity = _this.model.entities[k];
                    if (entity.type == 'menu--menu') {
                        dataPromises.push(_this.menuLoad(entity.attributes.id, attributes.cache));
                    }
                    if (entity.type == 'view--view') {
                        dataPromises.push(_this.getView(entity));
                    }
                    if (entity.data && entity.data.type.match('node--')) {
                        if (entity.data.attributes.uuid !== uuid) {
                            dataPromises.push(_this.jsonApi.getNode(entity.data.attributes.uuid));
                        }
                    }
                });
                _this.getSiteData(dataPromises).then(function () {
                    resolve();
                });
            });
        });
    };
    Drupal.prototype.getSiteData = function (promises) {
        var self = this;
        return new Promise(function (resolve) {
            Promise.all(promises).then(function () {
                if (self.cache) {
                    self.saveLocalModel(self.model, self.domain);
                }
                resolve();
            });
        });
    };
    Drupal.prototype.getLocalStorageCredentials = function () {
        var self = this;
        return new Promise(function (resolve, reject) {
            var credentials = self.api.getCredentials('drupal:authUser:' + self.domain);
            if (credentials) {
                for (var k in credentials) {
                    jDrupal.settings[k] = credentials[k];
                }
                var auth = atob(credentials.auth_hash);
                self.login(auth.split(':')[0], auth.split(':')[1]).then(function () {
                    resolve();
                });
            }
            else {
                resolve();
            }
        });
    };
    Drupal.prototype.menuLoad = function (mid, preloadNodes) {
        if (preloadNodes === void 0) { preloadNodes = false; }
        return __awaiter(this, void 0, void 0, function () {
            var self;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        self = this;
                        return [4 /*yield*/, new Promise(function (resolve, reject) {
                                self.api.get('entity/menu/' + mid + '/tree', { _format: 'hal_json' }).then(function (res) {
                                    var menu = res;
                                    self.model.menus[mid] = menu;
                                    if (preloadNodes) {
                                        var nids_1 = [];
                                        menu.forEach(function (item) {
                                            if (item.link.route_parameters.node) {
                                                nids_1.push(item.link.route_parameters.node);
                                            }
                                        });
                                        self.jsonApi.getNodes(nids_1).then(function () {
                                            resolve(menu);
                                        });
                                    }
                                    else {
                                        resolve(menu);
                                    }
                                });
                            })];
                    case 1:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    Drupal.prototype.bookLoad = function (bid, preload) {
        if (preload === void 0) { preload = false; }
        var self = this;
        return new Promise(function (resolve, reject) {
            self.api.get('rest/book_tree/' + bid, { _format: 'hal_json' }).then(function (res) {
                self.model.books[bid] = res;
                var nids = self.parseBookTree(bid);
                if (preload) {
                    self.jsonApi.getNodes(nids).then(function () {
                        resolve(res);
                    });
                }
                else {
                    resolve(res);
                }
            });
        });
    };
    Drupal.prototype.parseBookTree = function (bid) {
        var data = this.model.books[bid];
        var below, items, nids, k, kk;
        items = [];
        nids = [];
        for (k in data) {
            below = data[k].below;
        }
        for (k in below) {
            var item = void 0;
            for (kk in below[k]) {
                item = below[k];
                item.link.route_parameters = { node: below[k].link.nid };
                item.link.href = '/node/' + item.link.nid;
                nids.push(below[k].link.nid);
            }
            items.push(item);
        }
        this.model.menus['book_' + bid] = items;
        return nids;
    };
    // todo: remove: deprecated
    Drupal.prototype.nodeLoad = function (nid) {
        var self = this;
        return new Promise(function (resolve, reject) {
            if (self.cache && self.model.nodes[nid]) {
                resolve(self.model.nodes[nid]);
            }
            else {
                jDrupal.nodeLoad(nid).then(function (node) {
                    self.model.nodes[node.entity.nid[0].value] = node;
                    self.model.entities[node.entity.uuid[0].value] = node.entity;
                    resolve(node);
                });
            }
        });
    };
    // todo: remove: deprecated
    Drupal.prototype.nodesLoad = function (nids) {
        var self = this;
        var promises = [];
        return new Promise(function (resolve) {
            for (var k in nids) {
                promises.push(self.nodeLoad(nids[k]));
            }
            Promise.all(promises).then(function () {
                resolve();
            });
        });
    };
    // todo: remove: deprecated
    Drupal.prototype.createNode = function (data) {
        var node = {};
        for (var key in data) {
            node[key] = [{ value: data[key] }];
        }
        node.title = [{ value: data.title }];
        node.type = [{ target_id: data.type }];
        node._links = {
            type: {
                href: jDrupal.restPath() + 'rest/type/node/' + data.type
            }
        };
        // if(data.type==='iframe'){
        //     field_iframe: [ { target_id: data.type } ]
        // }
        return new jDrupal.Node(node);
    };
    // legacy: jDrupal
    Drupal.prototype.initJDrupal = function () {
        // @ts-ignore
        var jDrupal = {};
        jDrupal.init = function () { jDrupal.csrf_token = !1, jDrupal.sessid = null, jDrupal.modules = {}, jDrupal.connected = !1, jDrupal.settings = { sitePath: null, basePath: "/" }, "undefined" == typeof window && (global.Buffer = global.Buffer || require("buffer").Buffer, "undefined" == typeof btoa && (global.btoa = function (a) { return new Buffer(a).toString("base64"); }), "undefined" == typeof atob && (global.atob = function (a) { return new Buffer(a, "base64").toString(); })); }, jDrupal.init(), jDrupal.config = function (a) { var b = void 0 !== arguments[1] ? arguments[1] : null; return b ? void (jDrupal.settings[a] = b) : jDrupal.settings[a]; }, jDrupal.sitePath = function () { return jDrupal.settings.sitePath; }, jDrupal.basePath = function () { return jDrupal.settings.basePath; }, jDrupal.restPath = function () { return this.sitePath() + this.basePath(); }, jDrupal.path = function () { return this.restPath().substr(this.restPath().indexOf("://") + 3).replace("localhost", ""); }, jDrupal.isReady = function () { try {
            var a = !jDrupal.isEmpty(jDrupal.sitePath());
            return a || console.log("sitePath not setVar in jdrupal.settings.js"), a;
        }
        catch (b) {
            console.log("jDrupal.isReady - " + b);
        } }, jDrupal.isEmpty = function (a) { return null !== a && "object" == typeof a ? 0 === Object.keys(a).length : void 0 === a || null === a || "" == a; }, jDrupal.functionExists = function (name) { try {
            return "function" == eval("typeof " + name);
        }
        catch (error) {
            alert("jDrupal.functionExists - " + error);
        } }, jDrupal.inArray = function (a, b) { try {
            if (void 0 === b)
                return !1;
            if ("string" == typeof a)
                return b.indexOf(a) > -1;
            for (var c = !1, d = 0; d < b.length; d++)
                if (b[d] == a) {
                    c = !0;
                    break;
                }
            return c;
        }
        catch (e) {
            console.log("jDrupal.inArray - " + e);
        } }, jDrupal.isArray = function (a) { return "[object Array]" === Object.prototype.toString.call(a); }, jDrupal.isInt = function (a) { return "string" == typeof a && (a = parseInt(a)), "number" == typeof a && a % 1 == 0; }, jDrupal.isPromise = function (a) { return Promise.resolve(a) == a; }, jDrupal.shuffle = function (a) { for (var b = a.length - 1; b > 0; b--) {
            var c = Math.floor(Math.random() * (b + 1)), d = a[b];
            a[b] = a[c], a[c] = d;
        } return a; }, jDrupal.time = function () { var a = new Date; return Math.floor(a / 1e3); }, jDrupal.lcfirst = function (a) { return a += "", a.charAt(0).toLowerCase() + a.substr(1); }, jDrupal.ucfirst = function (a) { return a += "", a.charAt(0).toUpperCase() + a.substr(1); }, jDrupal.Module = function () { this.name = null; }, jDrupal.moduleExists = function (a) { try {
            return void 0 !== jDrupal.modules[a];
        }
        catch (b) {
            console.log("jDrupal.moduleExists - " + b);
        } }, jDrupal.moduleImplements = function (a) { try {
            var b = [];
            if (a)
                for (var c in jDrupal.modules)
                    jDrupal.modules.hasOwnProperty(c) && jDrupal.functionExists(c + "_" + a) && b.push(c);
            return 0 != b.length && b;
        }
        catch (d) {
            console.log("jDrupal.moduleImplements - " + d);
        } }, jDrupal.moduleInvoke = function (a, b) { if (jDrupal.moduleLoad(a)) {
            var c = a + "_" + b;
            if (jDrupal.functionExists(c)) {
                var d = window[c], e = Array.prototype.slice.call(arguments);
                return e.splice(0, 2), 0 == Object.getOwnPropertyNames(e).length ? d() : d.apply(null, e);
            }
        } }, jDrupal.moduleInvokeAll = function (a) { var b = [], c = Array.prototype.slice.call(arguments); c.splice(0, 1); var d = []; for (var e in jDrupal.modules)
            jDrupal.modules.hasOwnProperty(e) && jDrupal.functionExists(e + "_" + a) && d.push(e); if (jDrupal.isEmpty(d))
            return Promise.resolve(); for (var f = 0; f < d.length; f++) {
            0 == c.length ? b.push(jDrupal.moduleInvoke(d[f], a)) : (c.unshift(d[f], a), b.push(jDrupal.moduleInvoke.apply(null, c)), c.splice(0, 2));
        } return Promise.all(b); }, jDrupal.moduleLoad = function (a) { try {
            return !!jDrupal.modules[a] && jDrupal.modules[a];
        }
        catch (b) {
            console.log("jDrupal.moduleLoad - " + b);
        } }, jDrupal.modulesLoad = function () { return jDrupal.modules; }, function (a) { XMLHttpRequest.prototype.send = function (b) { var c = this, d = jDrupal.moduleInvokeAll("rest_pre_process", this, b); d ? d.then(function () { a.call(c, b); }) : a.call(this, b); }; }(XMLHttpRequest.prototype.send), jDrupal.token = function () { return new Promise(function (a, b) { var c = new XMLHttpRequest; c.dg = { service: "system", resource: "token" }, c.open("GET", jDrupal.restPath() + "rest/session/token"), c.onload = function () { if (200 == c.status) {
            var d = jDrupal.moduleInvokeAll("rest_post_process", c);
            d ? d.then(a(c.response)) : a(c.response);
        }
        else
            b(Error(c.statusText)); }, c.onerror = function () { b(Error("Network Error")); }, c.send(); }); }, jDrupal.connect = function () { return new Promise(function (a, b) { var c = new XMLHttpRequest; c.dg = { service: "system", resource: "connect" }, c.open("GET", jDrupal.restPath() + "jdrupal/connect?_format=json"); var d = function () { jDrupal.connected = !0; var b = JSON.parse(void 0 !== c.responseText ? c.responseText : c.response); 0 == b.uid ? (jDrupal.setCurrentUser(jDrupal.userDefaults()), a(b)) : jDrupal.userLoad(jDrupal.config("uid")).then(function (c) { jDrupal.setCurrentUser(c), a(b); }); }; c.onload = function () { if (200 != c.status)
            return void b(Error(c.statusText)); var a = jDrupal.moduleInvokeAll("rest_post_process", c); a ? a.then(d) : d(); }, c.onerror = function () { b(Error("Network Error")); }, c.send(); }); }, jDrupal.userLogin = function (a, b) { return new Promise(function (c, d) { var e = new XMLHttpRequest; e.dg = { service: "user", resource: "login" }, e.open("POST", jDrupal.restPath() + "user/login?_format=json"), e.setRequestHeader("Content-type", "application/json"); e.onload = function () { if (JSON.parse(e.responseText).current_user && (jDrupal.settings.uid = JSON.parse(e.responseText).current_user.uid, jDrupal.settings.user_csrf_token = JSON.parse(e.responseText).csrf_token, jDrupal.settings.user_logout_token = JSON.parse(e.responseText).logout_token, jDrupal.settings.auth_hash = btoa(a + ":" + b), jDrupal.userLoad(jDrupal.config("uid")).then(function (a) { jDrupal.setCurrentUser(a), c(a); })), 200 == e.status) {
            jDrupal.moduleInvokeAll("rest_post_process", e);
        }
        else
            d(Error(e.statusText)); }, e.onerror = function () { d(Error("Network Error")); }, e.send(JSON.stringify({ name: a, pass: b })); }); }, jDrupal.userLogout = function () { return new Promise(function (a, b) { var c = new XMLHttpRequest; c.dg = { service: "user", resource: "logout" }, c.open("GET", jDrupal.restPath() + "user/logout?_format=hal+json&token=" + jDrupal.settings.user_logout_token), c.setRequestHeader("Content-type", "application/json"); var d = function () { jDrupal.setCurrentUser(jDrupal.userDefaults()), jDrupal.connect().then(a); }; c.onload = function () { if (200 == c.status || 303 == c.status) {
            var a = jDrupal.moduleInvokeAll("rest_post_process", c);
            a ? a.then(d) : d();
        }
        else
            b(Error(c.statusText)); }, c.onerror = function () { b(Error("Network Error")); }, c.send(); }); }, jDrupal.entityLoad = function (a, b) { return new (this[this.ucfirst(a)])(b).load(); }, jDrupal.commentLoad = function (a) { return this.entityLoad("comment", a); }, jDrupal.nodeLoad = function (a) { return this.entityLoad("node", a); }, jDrupal.userLoad = function (a) { return this.entityLoad("user", a); }, jDrupal.userRegister = function (a, b, c) { return new Promise(function (d, e) { jDrupal.token().then(function (f) { var g = new XMLHttpRequest; g.dg = { service: "user", resource: "register" }, g.open("POST", jDrupal.restPath() + "user/register?_format=hal_json"), g.setRequestHeader("Content-type", "application/json"), g.setRequestHeader("Authorization", "Basic " + jDrupal.settings.auth_hash), g.setRequestHeader("X-CSRF-Token", f); var h = function () { jDrupal.connect().then(d); }; g.onload = function () { if (200 == g.status) {
            var a = jDrupal.moduleInvokeAll("rest_post_process", g);
            a ? a.then(h) : h();
        }
        else
            e(Error(g.statusText)); }, g.onerror = function () { e(Error("Network Error")); }, g.send(JSON.stringify({ name: { value: a }, pass: { value: b }, mail: { value: c } })); }); }); }, jDrupal.Views = function (a) { this.path = a, this.results = null; }, jDrupal.Views.prototype.getPath = function () { return this.path; }, jDrupal.Views.prototype.getResults = function () { return this.results; }, jDrupal.Views.prototype.getView = function () { var a = this; return new Promise(function (b, c) { var d = new XMLHttpRequest; d.dg = { service: "views", resource: null }, d.open("GET", jDrupal.restPath() + a.getPath()); var e = function () { a.results = JSON.parse(d.response), b(); }; d.onload = function () { if (200 == d.status) {
            var a = jDrupal.moduleInvokeAll("rest_post_process", d);
            a ? a.then(e) : e();
        }
        else
            c(Error(d.statusText)); }, d.onerror = function () { c(Error("Network Error")); }, d.send(); }); }, jDrupal.viewsLoad = function (a) { return new Promise(function (b, c) { var d = new jDrupal.Views(a); d.getView().then(function () { b(d); }); }); }, jDrupal.Entity = function (a, b, c) { this.entity = null, this.bundle = b, this.entityID = c, this.entityKeys = {}; }, jDrupal.Entity.prototype.getVar = function (a, b) { return this.entity && void 0 !== this.entity[a] ? void 0 !== b ? this.entity[a][b] : this.entity[a] : null; }, jDrupal.Entity.prototype.setVar = function (a, b, c) { this.entity && (void 0 !== b && void 0 !== this.entity[a] ? this.entity[a][b] = c : this.entity[a] = c); }, jDrupal.Entity.prototype.getEntityKey = function (a) { return void 0 !== this.entityKeys[a] ? this.entityKeys[a] : null; }, jDrupal.Entity.prototype.getEntityType = function () { return this.entityKeys.type; }, jDrupal.Entity.prototype.getBundle = function () { var a = this.getEntityKey("bundle"); return void 0 !== this.entity[a] ? this.entity[a][0].target_id : null; }, jDrupal.Entity.prototype.id = function () { var a = this.getEntityKey("id"); return void 0 !== this.entity[a] ? this.entity[a][0].value : null; }, jDrupal.Entity.prototype.language = function () { return this.entity.langcode[0].value; }, jDrupal.Entity.prototype.isNew = function () { return !this.id(); }, jDrupal.Entity.prototype.label = function () { var a = this.getEntityKey("label"); return void 0 !== this.entity[a] ? this.entity[a][0].value : null; }, jDrupal.Entity.prototype.stringify = function () { return JSON.stringify(this.entity); }, jDrupal.Entity.prototype.preLoad = function (a) { return new Promise(function (a, b) { a(); }); }, jDrupal.Entity.prototype.load = function () { try {
            var a = this, b = a.getEntityType();
            return new Promise(function (c, d) { a.preLoad().then(function () { var e = jDrupal.restPath() + b + "/" + a.id() + "?_format=hal_json", f = new XMLHttpRequest; f.dg = { service: b, resource: "retrieve" }, f.open("GET", e), jDrupal.settings.auth_hash && f.setRequestHeader("Authorization", "Basic " + jDrupal.settings.auth_hash); var g = function () { a.entity = JSON.parse(f.response), a.postLoad(f).then(function () { c(a); }); }; f.onload = function () { if (200 == f.status) {
                var a = jDrupal.moduleInvokeAll("rest_post_process", f);
                a ? a.then(g) : g();
            }
            else
                d(Error(f.statusText)); }, f.onerror = function () { d(Error("Network Error")); }, f.send(); }); });
        }
        catch (c) {
            console.log("jDrupal.Entity.load - " + c);
        } }, jDrupal.Entity.prototype.postLoad = function (a) { return new Promise(function (a, b) { a(); }); }, jDrupal.Entity.prototype.preSave = function (a) { return new Promise(function (a, b) { a(); }); }, jDrupal.Entity.prototype.save = function () { var a = this; return new Promise(function (b, c) { a.preSave().then(function () { jDrupal.token().then(function (d) { var e = a.getEntityType(), f = null, g = null, h = null; a.isNew() ? (f = "POST", g = "create", h = "entity/" + e) : (f = "PATCH", g = "update", h = e + "/" + a.id()); var i = new XMLHttpRequest; i.dg = { service: e, resource: g }, i.open(f, jDrupal.restPath() + h + "?_format=hal_json"), i.setRequestHeader("Accept", "application/json"), i.setRequestHeader("Authorization", "Basic " + jDrupal.settings.auth_hash), i.setRequestHeader("Content-Type", "application/hal+json"), i.setRequestHeader("X-CSRF-Token", d), i.onload = function () { a.postSave(i).then(function () { if ("POST" == f && 201 == i.status || "PATCH" == f && 204 == i.status || 200 == i.status) {
            var a = jDrupal.moduleInvokeAll("rest_post_process", i);
            a ? a.then(b) : b();
        }
        else
            c(Error(i.statusText)); }); }, i.onerror = function () { c(Error("Network Error")); }, i.send(a.stringify()); }); }); }); }, jDrupal.Entity.prototype.postSave = function (a) { var b = this; return new Promise(function (c, d) { if (b.isNew() && a.getResponseHeader("Location")) {
            var e = a.getResponseHeader("Location").split("/");
            b.entity[b.getEntityKey("id")] = [{ value: e[e.length - 1] }];
        } c(); }); }, jDrupal.Entity.prototype.preDelete = function (a) { return new Promise(function (a, b) { a(); }); }, jDrupal.Entity.prototype.delete = function (a) { var b = this; return new Promise(function (a, c) { b.preDelete().then(function () { jDrupal.token().then(function (d) { var e = b.getEntityType(), f = jDrupal.restPath() + e + "/" + b.id(), g = {}; g[b.getEntityKey("bundle")] = [{ target_id: b.getBundle() }], "node" === e && (g._links = { type: { href: jDrupal.restPath() + "rest/type/node/" + b.getBundle() } }); var h = new XMLHttpRequest; h.dg = { service: e, resource: "delete" }, h.open("DELETE", f), h.setRequestHeader("Content-type", "application/hal+json"), h.setRequestHeader("Accept", "application/json"), h.setRequestHeader("Authorization", "Basic " + jDrupal.settings.auth_hash), h.setRequestHeader("X-CSRF-Token", d), h.onload = function () { b.postDelete(h).then(function () { if (204 == h.status) {
            var b = jDrupal.moduleInvokeAll("rest_post_process", h);
            b ? b.then(a) : a();
        }
        else
            c(Error(h.statusText)); }); }, h.onerror = function () { c(Error("Network Error")); }, h.send(JSON.stringify(g)); }); }); }); }, jDrupal.Entity.prototype.postDelete = function (a) { var b = this; return new Promise(function (a, c) { b.entity = null, a(); }); }, jDrupal.entityConstructorPrep = function (a, b) { if (b)
            if ("object" == typeof b)
                a.entity = b;
            else {
                var c = a.getEntityKey("id"), d = {};
                d[c] = [{ value: b }], a.entity = d;
            }
        else
            ; }, jDrupal.Comment = function (a) { this.entityKeys.type = "comment", this.entityKeys.bundle = "comment_type", this.entityKeys.id = "cid", this.entityKeys.label = "subject", jDrupal.entityConstructorPrep(this, a); }, jDrupal.Comment.prototype = new jDrupal.Entity, jDrupal.Comment.prototype.constructor = jDrupal.Comment, jDrupal.Comment.prototype.getSubject = function () { return this.entity.subject[0].value; }, jDrupal.Comment.prototype.setSubject = function (a) { try {
            this.entity.subject[0].value = a;
        }
        catch (b) {
            console.log("jDrupal.Comment.setSubject - " + b);
        } }, jDrupal.Comment.prototype.preSave = function (a) { return new Promise(function (a, b) { a(); }); }, jDrupal.Comment.prototype.stringify = function () { try {
            if (!this.isNew()) {
                for (var a = JSON.parse(JSON.stringify(this.entity)), b = ["hostname", "changed", "cid", "thread", "uuid", "entity_id", "entity_type", "pid", "field_name", "created", "name", "mail", "homepage"], c = 0; c < b.length; c++)
                    void 0 !== a[b[c]] && delete a[b[c]];
                return JSON.stringify(a);
            }
            return JSON.stringify(this.entity);
        }
        catch (d) {
            console.log("jDrupal.Comment.stringify - " + d);
        } }, jDrupal.Node = function (a) { this.entityKeys.type = "node", this.entityKeys.bundle = "type", this.entityKeys.id = "nid", this.entityKeys.label = "title", jDrupal.entityConstructorPrep(this, a), this.entity && (this.entity.title || (this.entity.title = [{ value: "" }])); }, jDrupal.Node.prototype = new jDrupal.Entity, jDrupal.Node.prototype.constructor = jDrupal.Node, jDrupal.Node.prototype.getTitle = function () { return this.label(); }, jDrupal.Node.prototype.setTitle = function (a) { try {
            this.entity.title[0].value = a;
        }
        catch (b) {
            console.log("jDrupal.Node.setTitle - " + b);
        } }, jDrupal.Node.prototype.getType = function () { return this.getBundle(); }, jDrupal.Node.prototype.getCreatedTime = function () { return this.entity.created[0].value; }, jDrupal.Node.prototype.isPromoted = function () { return this.entity.promote[0].value; }, jDrupal.Node.prototype.isPublished = function () { return this.entity.status[0].value; }, jDrupal.Node.prototype.isSticky = function () { return this.entity.sticky[0].value; }, jDrupal.Node.prototype.preSave = function (a) { var b = this; return new Promise(function (a, c) { for (var d = ["_embedded", "changed", "revision_timestamp", "revision_uid", "revision_translation_affected"], e = 0; e < d.length; e++)
            delete b.entity[d[e]]; a(); }); }, jDrupal.User = function (a) { this.entityKeys.type = "user", this.entityKeys.bundle = "user", this.entityKeys.id = "uid", this.entityKeys.label = "name", jDrupal.entityConstructorPrep(this, a); }, jDrupal.User.prototype = new jDrupal.Entity, jDrupal.User.prototype.constructor = jDrupal.User, jDrupal.User.prototype.getAccountName = function () { return this.label(); }, jDrupal.User.prototype.getRoles = function () { for (var a = (this.entity.roles, []), b = 0; b < this.entity.roles.length; b++)
            a.push(this.entity.roles[b].target_id); return a; }, jDrupal.User.prototype.hasRole = function (a) { return jDrupal.inArray(a, this.getRoles()); }, jDrupal.User.prototype.isAnonymous = function () { return 0 == this.id(); }, jDrupal.User.prototype.isAuthenticated = function () { return !this.isAnonymous(); }, jDrupal.currentUser = function () { return jDrupal._currentUser; }, jDrupal.User.prototype.postLoad = function (a) { var b = this; return new Promise(function (a, c) { b.entity.roles || (b.entity.roles = [{ target_id: "authenticated" }]), a(); }); }, jDrupal.userDefaults = function () { return new jDrupal.User({ uid: [{ value: 0 }], roles: [{ target_id: "anonymous" }] }); }, jDrupal.setCurrentUser = function (a) { a.isAuthenticated() && !jDrupal.inArray("authenticated", a.getRoles()) && a.entity.roles.push({ target_id: "authenticated" }), jDrupal._currentUser = a; }, jDrupal.userPassword = function () { var a = 10; arguments[0] && (a = arguments[0]); for (var b = "", c = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz23456789", d = 0; d < a; d++)
            b += c.charAt(Math.floor(Math.random() * c.length)); return b; };
        util_1.Util.getGlobal()['jDrupal'] = jDrupal;
    };
    ;
    return Drupal;
}());
exports.Drupal = Drupal;
//# sourceMappingURL=drupal.js.map