/**
 * @fileoverview added by tsickle
 * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
 */
import * as tslib_1 from "tslib";
import { BaseApi } from '../../base/base-api';
import { Util } from '../../utils/util';
var DrupalApi = /** @class */ (function (_super) {
    tslib_1.__extends(DrupalApi, _super);
    function DrupalApi() {
        var _this = _super.call(this) || this;
        _this.cache = false;
        _this.collections = {};
        _this.entities = {};
        _this.nodes = {};
        _this.resources = {};
        _this.views = {};
        _this.headers = {
            'Accept': 'application/vnd.api+json',
            'Content-Type': 'application/vnd.api+json'
        };
        return _this;
    }
    /**
     * @param {?} path
     * @param {?} object
     * @return {?}
     */
    DrupalApi.prototype.post = /**
     * @param {?} path
     * @param {?} object
     * @return {?}
     */
    function (path, object) {
        return tslib_1.__awaiter(this, void 0, void 0, function () {
            return tslib_1.__generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        this.headers['Authorization'] = 'Basic ' + jDrupal.settings.auth_hash;
                        this.headers['X-CSRF-Token'] = jDrupal.settings.user_csrf_token;
                        this.headers['Content-Type'] = 'application/vnd.api+json';
                        return [4 /*yield*/, fetch("" + this.baseUrl + path, {
                                headers: this.headers,
                                method: 'POST',
                                body: JSON.stringify(object)
                            })];
                    case 1:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    /**
     * @param {?} path
     * @param {?} id
     * @param {?} object
     * @return {?}
     */
    DrupalApi.prototype.patch = /**
     * @param {?} path
     * @param {?} id
     * @param {?} object
     * @return {?}
     */
    function (path, id, object) {
        return tslib_1.__awaiter(this, void 0, void 0, function () {
            return tslib_1.__generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        this.headers['Authorization'] = 'Basic ' + jDrupal.settings.auth_hash;
                        this.headers['X-CSRF-Token'] = jDrupal.settings.user_csrf_token;
                        this.headers['Content-Type'] = 'application/vnd.api+json';
                        if (object.data.attributes.changed) {
                            object.data.attributes.changed = undefined;
                        }
                        return [4 /*yield*/, fetch("" + this.baseUrl + path + "/" + id, {
                                headers: this.headers,
                                method: 'PATCH',
                                body: JSON.stringify(object)
                            })];
                    case 1:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    // FIXME: causes php server error on drupal content admin page
    // FIXME: causes php server error on drupal content admin page
    /**
     * @param {?} path
     * @param {?} id
     * @return {?}
     */
    DrupalApi.prototype.delete = 
    // FIXME: causes php server error on drupal content admin page
    /**
     * @param {?} path
     * @param {?} id
     * @return {?}
     */
    function (path, id) {
        return tslib_1.__awaiter(this, void 0, void 0, function () {
            return tslib_1.__generator(this, function (_a) {
                console.log('FIXME drupal delete');
                console.log(path, id);
                this.headers['Authorization'] = 'Basic ' + jDrupal.settings.auth_hash;
                this.headers['X-CSRF-Token'] = jDrupal.settings.user_csrf_token;
                this.headers['Content-Type'] = 'application/vnd.api+json';
                return [2 /*return*/];
            });
        });
    };
    /**
     * @param {?=} jsonapi_endpoint
     * @param {?=} language
     * @return {?}
     */
    DrupalApi.prototype.getResourcesIndex = /**
     * @param {?=} jsonapi_endpoint
     * @param {?=} language
     * @return {?}
     */
    function (jsonapi_endpoint, language) {
        if (jsonapi_endpoint === void 0) { jsonapi_endpoint = 'jsonapi'; }
        if (language === void 0) { language = undefined; }
        return tslib_1.__awaiter(this, void 0, void 0, function () {
            var self;
            return tslib_1.__generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        self = this;
                        return [4 /*yield*/, new Promise((/**
                             * @param {?} resolve
                             * @param {?} reject
                             * @return {?}
                             */
                            function (resolve, reject) {
                                /** @type {?} */
                                var url = self.baseUrl + 'index.php/';
                                if (language) {
                                    url += language + '/';
                                }
                                url += jsonapi_endpoint;
                                fetch(url)
                                    .then((/**
                                 * @param {?} response
                                 * @return {?}
                                 */
                                function (response) {
                                    if (response.status >= 400) {
                                        throw new Error('JsonApi: Bad resources response from server');
                                    }
                                    return response.json();
                                }))
                                    .then((/**
                                 * @param {?} result
                                 * @return {?}
                                 */
                                function (result) {
                                    self.resources = result;
                                    self.baseUrl = result.links.self + '/';
                                    Object.keys(result.links).forEach((/**
                                     * @param {?} k
                                     * @param {?} i
                                     * @return {?}
                                     */
                                    function (k, i) {
                                        if (k.match('node--')
                                            || k.match('menu--')
                                            || k.match('comment--')
                                            || k.match('file--')
                                            || k.match('taxonomy_term--')
                                            || k.match('node_type--')
                                        // || k.match('view--')
                                        ) {
                                            self.collections[k] = {};
                                        }
                                    }));
                                    resolve(result);
                                }));
                            }))];
                    case 1:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    ;
    /**
     * @param {?} collectionId
     * @param {?=} params
     * @param {?=} getRelationships
     * @return {?}
     */
    DrupalApi.prototype.getCollection = /**
     * @param {?} collectionId
     * @param {?=} params
     * @param {?=} getRelationships
     * @return {?}
     */
    function (collectionId, params, getRelationships) {
        if (params === void 0) { params = undefined; }
        if (getRelationships === void 0) { getRelationships = false; }
        return tslib_1.__awaiter(this, void 0, void 0, function () {
            var path, collection, _a, _b, relatedPromises_1, _c, _d, _i, k;
            var _this = this;
            return tslib_1.__generator(this, function (_e) {
                switch (_e.label) {
                    case 0:
                        path = collectionId.split('--')[0] + '/' + collectionId.split('--')[1];
                        _a = this.collections;
                        _b = collectionId;
                        return [4 /*yield*/, this.get(path, {})];
                    case 1:
                        collection = _a[_b] = _e.sent();
                        if (!getRelationships) return [3 /*break*/, 5];
                        relatedPromises_1 = [];
                        Object.keys(collection.data).forEach((/**
                         * @param {?} k
                         * @return {?}
                         */
                        function (k) {
                            relatedPromises_1.push(_this.getEntityRelationships({ data: collection.data[k] }));
                        }));
                        _c = [];
                        for (_d in relatedPromises_1)
                            _c.push(_d);
                        _i = 0;
                        _e.label = 2;
                    case 2:
                        if (!(_i < _c.length)) return [3 /*break*/, 5];
                        k = _c[_i];
                        return [4 /*yield*/, relatedPromises_1[k]];
                    case 3:
                        _e.sent();
                        _e.label = 4;
                    case 4:
                        _i++;
                        return [3 /*break*/, 2];
                    case 5:
                        Object.keys(collection.data).forEach((/**
                         * @param {?} k
                         * @param {?} i
                         * @return {?}
                         */
                        function (k, i) {
                            _this.entities[collection.data[k].attributes.uuid] = collection.data[k];
                        }));
                        return [2 /*return*/, collection];
                }
            });
        });
    };
    /**
     * @param {?} collectionIds
     * @param {?=} params
     * @param {?=} getRelationships
     * @return {?}
     */
    DrupalApi.prototype.getCollections = /**
     * @param {?} collectionIds
     * @param {?=} params
     * @param {?=} getRelationships
     * @return {?}
     */
    function (collectionIds, params, getRelationships) {
        if (params === void 0) { params = undefined; }
        if (getRelationships === void 0) { getRelationships = false; }
        return tslib_1.__awaiter(this, void 0, void 0, function () {
            var promises, _a, _b, _i, k;
            var _this = this;
            return tslib_1.__generator(this, function (_c) {
                switch (_c.label) {
                    case 0:
                        promises = [];
                        collectionIds.forEach((/**
                         * @param {?} id
                         * @return {?}
                         */
                        function (id) {
                            promises.push(_this.getCollection(id, params, getRelationships));
                        }));
                        _a = [];
                        for (_b in promises)
                            _a.push(_b);
                        _i = 0;
                        _c.label = 1;
                    case 1:
                        if (!(_i < _a.length)) return [3 /*break*/, 4];
                        k = _a[_i];
                        return [4 /*yield*/, promises[k]];
                    case 2:
                        _c.sent();
                        _c.label = 3;
                    case 3:
                        _i++;
                        return [3 /*break*/, 1];
                    case 4: return [2 /*return*/];
                }
            });
        });
    };
    /**
     * @param {?=} getRelationships
     * @param {?=} exclude
     * @return {?}
     */
    DrupalApi.prototype.getAllCollections = /**
     * @param {?=} getRelationships
     * @param {?=} exclude
     * @return {?}
     */
    function (getRelationships, exclude) {
        if (getRelationships === void 0) { getRelationships = false; }
        if (exclude === void 0) { exclude = []; }
        return tslib_1.__awaiter(this, void 0, void 0, function () {
            var promises, _a, _b, _i, k;
            var _this = this;
            return tslib_1.__generator(this, function (_c) {
                switch (_c.label) {
                    case 0:
                        promises = [];
                        Object.keys(this.collections).forEach((/**
                         * @param {?} k
                         * @param {?} i
                         * @return {?}
                         */
                        function (k, i) {
                            /** @type {?} */
                            var excluded = false;
                            exclude.forEach((/**
                             * @param {?} id
                             * @return {?}
                             */
                            function (id) {
                                if (id === k) {
                                    excluded = true;
                                }
                            }));
                            if (!excluded) {
                                promises.push(_this.getCollection(k, {}, getRelationships));
                            }
                        }));
                        _a = [];
                        for (_b in promises)
                            _a.push(_b);
                        _i = 0;
                        _c.label = 1;
                    case 1:
                        if (!(_i < _a.length)) return [3 /*break*/, 4];
                        k = _a[_i];
                        return [4 /*yield*/, promises[k]];
                    case 2:
                        _c.sent();
                        _c.label = 3;
                    case 3:
                        _i++;
                        return [3 /*break*/, 1];
                    case 4: return [2 /*return*/];
                }
            });
        });
    };
    /**
     * @param {?} url
     * @param {?=} params
     * @return {?}
     */
    DrupalApi.prototype.getResource = /**
     * @param {?} url
     * @param {?=} params
     * @return {?}
     */
    function (url, params) {
        if (params === void 0) { params = undefined; }
        return tslib_1.__awaiter(this, void 0, void 0, function () {
            var resource;
            var _this = this;
            return tslib_1.__generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (params) {
                            url += '?';
                            Object.keys(params).forEach((/**
                             * @param {?} key
                             * @return {?}
                             */
                            function (key) { return url += key + '=' + params[key] + '&'; }));
                        }
                        return [4 /*yield*/, fetch(url, { headers: this.headers })
                                .then((/**
                             * @param {?} response
                             * @return {?}
                             */
                            function (response) {
                                if (response.status >= 400) {
                                    throw new Error('Bad response from server');
                                }
                                return response.json();
                            }))
                                .then((/**
                             * @param {?} data
                             * @return {?}
                             */
                            function (data) {
                                // setVar entity + getVar relationships
                                if (data.data && data.data.id) {
                                    _this.entities[data.data.id] = data;
                                }
                                // setVar entities array + getVar relationships
                                if (data.data && Array.isArray(data.data)) {
                                    data.data.forEach((/**
                                     * @param {?} item
                                     * @return {?}
                                     */
                                    function (item) {
                                        if (item.id) {
                                            _this.entities[item.id] = item;
                                        }
                                    }));
                                }
                                return data;
                            }))];
                    case 1:
                        resource = _a.sent();
                        return [2 /*return*/, resource];
                }
            });
        });
    };
    /**
     * @param {?} urls
     * @return {?}
     */
    DrupalApi.prototype.getResources = /**
     * @param {?} urls
     * @return {?}
     */
    function (urls) {
        return tslib_1.__awaiter(this, void 0, void 0, function () {
            var promises, _a, _b, _i, k;
            var _this = this;
            return tslib_1.__generator(this, function (_c) {
                switch (_c.label) {
                    case 0:
                        promises = [];
                        urls.forEach((/**
                         * @param {?} url
                         * @return {?}
                         */
                        function (url) {
                            promises.push(_this.getResource(url));
                        }));
                        _a = [];
                        for (_b in promises)
                            _a.push(_b);
                        _i = 0;
                        _c.label = 1;
                    case 1:
                        if (!(_i < _a.length)) return [3 /*break*/, 4];
                        k = _a[_i];
                        return [4 /*yield*/, promises[k]];
                    case 2:
                        _c.sent();
                        _c.label = 3;
                    case 3:
                        _i++;
                        return [3 /*break*/, 1];
                    case 4: return [2 /*return*/];
                }
            });
        });
    };
    // todo:
    // todo:
    /**
     * @param {?} entity
     * @return {?}
     */
    DrupalApi.prototype.getEntityRelationships = 
    // todo:
    /**
     * @param {?} entity
     * @return {?}
     */
    function (entity) {
        return tslib_1.__awaiter(this, void 0, void 0, function () {
            var _this = this;
            return tslib_1.__generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, new Promise((/**
                         * @param {?} resolve
                         * @return {?}
                         */
                        function (resolve) {
                            /** @type {?} */
                            var relationships = [];
                            if (entity.data && entity.data.relationships) {
                                Object.keys(entity.data.relationships).forEach((/**
                                 * @param {?} k
                                 * @param {?} i
                                 * @return {?}
                                 */
                                function (k, i) {
                                    // todo: nodes only: check other entity relation types
                                    if (k.match('field_')) {
                                        relationships.push(entity.data.relationships[k]);
                                    }
                                }));
                            }
                            if (relationships.length) {
                                /** @type {?} */
                                var urls_1 = [];
                                relationships.forEach((/**
                                 * @param {?} relationship
                                 * @return {?}
                                 */
                                function (relationship) {
                                    if (relationship.links && relationship.links.self) {
                                        urls_1.push(relationship.links.related);
                                    }
                                }));
                                if (urls_1.length) {
                                    _this.getResources(urls_1).then((/**
                                     * @return {?}
                                     */
                                    function () {
                                        // console.log(urls);
                                        resolve();
                                    }));
                                }
                                else {
                                    resolve();
                                }
                            }
                            else {
                                resolve();
                            }
                        }))];
                    case 1: 
                    // console.log(entity);
                    return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    /**
     * @param {?} id
     * @param {?=} type
     * @return {?}
     */
    DrupalApi.prototype.getNode = /**
     * @param {?} id
     * @param {?=} type
     * @return {?}
     */
    function (id, type) {
        if (type === void 0) { type = undefined; }
        return tslib_1.__awaiter(this, void 0, void 0, function () {
            var self, idField;
            var _this = this;
            return tslib_1.__generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        self = this;
                        id = Util.castToType(id);
                        idField = 'uuid';
                        if (typeof id === 'number') {
                            idField = 'nid';
                        }
                        return [4 /*yield*/, new Promise((/**
                             * @param {?} resolve
                             * @return {?}
                             */
                            function (resolve) {
                                /** @type {?} */
                                var path;
                                // cached node
                                if (_this.cache) {
                                    /** @type {?} */
                                    var cachedNode_1;
                                    Object.keys(_this.entities).forEach((/**
                                     * @param {?} k
                                     * @return {?}
                                     */
                                    function (k) {
                                        if (_this.entities[k].data && _this.entities[k].data.attributes[idField] == id) {
                                            cachedNode_1 = _this.entities[k];
                                        }
                                    }));
                                    if (cachedNode_1) {
                                        resolve(cachedNode_1);
                                        return;
                                    }
                                }
                                // define type from node_index view
                                if (_this.views['node_index']) {
                                    _this.views['node_index'].forEach((/**
                                     * @param {?} item
                                     * @return {?}
                                     */
                                    function (item) {
                                        if (item[idField] == id) {
                                            type = item.type;
                                        }
                                    }));
                                }
                                if (type) {
                                    path = 'node/' + type;
                                    _this.get(path + '?filter[' + idField + '][value]=' + id).then((/**
                                     * @param {?} res
                                     * @return {?}
                                     */
                                    function (res) {
                                        parseNodeResult(res);
                                    }));
                                }
                                else {
                                    // search through all node collections
                                    /** @type {?} */
                                    var nodeTypes_1 = [];
                                    Object.keys(_this.collections).forEach((/**
                                     * @param {?} k
                                     * @return {?}
                                     */
                                    function (k) {
                                        if (k.match('node--')) {
                                            nodeTypes_1.push(k);
                                        }
                                    }));
                                    nodeTypes_1.forEach((/**
                                     * @param {?} type
                                     * @return {?}
                                     */
                                    function (type) {
                                        /** @type {?} */
                                        var path = type.split('--')[0] + '/' + type.split('--')[1];
                                        // fixme: stop further http requests after node match response
                                        _this.get(path + '?filter[' + idField + '][value]=' + id).then((/**
                                         * @param {?} res
                                         * @return {?}
                                         */
                                        function (res) {
                                            parseNodeResult(res);
                                        }));
                                    }));
                                }
                                /**
                                 * @param {?} res
                                 * @return {?}
                                 */
                                function parseNodeResult(res) {
                                    if (res && res.data && res.data.length) {
                                        /** @type {?} */
                                        var node_1 = { data: res.data[0] };
                                        self.entities[res.data[0].id] = node_1;
                                        if (!self.collections[res.data[0].type].data) {
                                            self.collections[res.data[0].type].data = [];
                                        }
                                        // fixme: todo: check for doubles before push
                                        self.collections[res.data[0].type].data.push(node_1);
                                        // todo: deprecate, use collections + entities only
                                        self.nodes[res.data[0].attributes.nid] = node_1;
                                        // getVar relationships
                                        if (node_1.data.relationships) {
                                            self.getEntityRelationships(node_1).then((/**
                                             * @return {?}
                                             */
                                            function () {
                                                resolve(node_1);
                                            }));
                                        }
                                    }
                                }
                            }))];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    /**
     * @param {?} ids
     * @return {?}
     */
    DrupalApi.prototype.getNodes = /**
     * @param {?} ids
     * @return {?}
     */
    function (ids) {
        return tslib_1.__awaiter(this, void 0, void 0, function () {
            var promises, _a, _b, _i, k;
            var _this = this;
            return tslib_1.__generator(this, function (_c) {
                switch (_c.label) {
                    case 0:
                        promises = [];
                        ids.forEach((/**
                         * @param {?} id
                         * @return {?}
                         */
                        function (id) {
                            promises.push(_this.getNode(id));
                        }));
                        _a = [];
                        for (_b in promises)
                            _a.push(_b);
                        _i = 0;
                        _c.label = 1;
                    case 1:
                        if (!(_i < _a.length)) return [3 /*break*/, 4];
                        k = _a[_i];
                        return [4 /*yield*/, promises[k]];
                    case 2:
                        _c.sent();
                        _c.label = 3;
                    case 3:
                        _i++;
                        return [3 /*break*/, 1];
                    case 4: return [2 /*return*/];
                }
            });
        });
    };
    /**
     * @param {?} node
     * @return {?}
     */
    DrupalApi.prototype.saveNode = /**
     * @param {?} node
     * @return {?}
     */
    function (node) {
        return tslib_1.__awaiter(this, void 0, void 0, function () {
            var path;
            return tslib_1.__generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        path = node.data.type.split('--')[0] + '/' + node.data.type.split('--')[1];
                        if (!!node.data.id) return [3 /*break*/, 2];
                        return [4 /*yield*/, this.post(path, node)];
                    case 1:
                        _a.sent();
                        return [3 /*break*/, 4];
                    case 2: return [4 /*yield*/, this.patch(path, node.data.id, node)];
                    case 3:
                        _a.sent();
                        _a.label = 4;
                    case 4: return [2 /*return*/];
                }
            });
        });
    };
    /**
     * @param {?} node
     * @return {?}
     */
    DrupalApi.prototype.deleteNode = /**
     * @param {?} node
     * @return {?}
     */
    function (node) {
        return tslib_1.__awaiter(this, void 0, void 0, function () {
            var path;
            return tslib_1.__generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        path = node.data.type.split('--')[0] + '/' + node.data.type.split('--')[1];
                        return [4 /*yield*/, this.delete(path, node.data.id).then((/**
                             * @param {?} arg
                             * @return {?}
                             */
                            function (arg) {
                                // fixme: todo: delete from collections + entities
                                // if (this.entities[node.data.id]){
                                //     this.entities[node.data.id] = undefined;
                                // }
                                // let collection = this.collections[node.data.type];
                                // if(collection.data && collection.data.length) {
                                //     collection.data.forEach((collectionNode,i) => {
                                //         if(node.data.id === collectionNode.data.id){
                                //             // collection.data.slice(i)
                                //         }
                                //     });
                                // }
                            }))];
                    case 1:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    // todo: check?
    // todo: check?
    /**
     * @param {?} entity_id
     * @return {?}
     */
    DrupalApi.prototype.getById = 
    // todo: check?
    /**
     * @param {?} entity_id
     * @return {?}
     */
    function (entity_id) {
        var _this = this;
        /** @type {?} */
        var entity;
        Object.keys(this.collections).forEach((/**
         * @param {?} k
         * @param {?} i
         * @return {?}
         */
        function (k, i) {
            if (_this.collections[k]['data'] && _this.collections[k]['data'].length) {
                _this.collections[k]['data'].forEach((/**
                 * @param {?} entityObject
                 * @return {?}
                 */
                function (entityObject) {
                    if (entityObject.id === entity_id) {
                        entity = entityObject;
                    }
                }));
            }
        }));
        if (entity) {
            return { data: entity };
        }
        // return entity;
    };
    /**
     * @param {?} nid
     * @return {?}
     */
    DrupalApi.prototype.getByNodeId = /**
     * @param {?} nid
     * @return {?}
     */
    function (nid) {
        return tslib_1.__awaiter(this, void 0, void 0, function () {
            var entity;
            var _this = this;
            return tslib_1.__generator(this, function (_a) {
                Object.keys(this.collections).forEach((/**
                 * @param {?} k
                 * @param {?} i
                 * @return {?}
                 */
                function (k, i) {
                    if (k.match('node--') && _this.collections[k]['data'] && _this.collections[k]['data'].length) {
                        _this.collections[k]['data'].forEach((/**
                         * @param {?} entityObject
                         * @return {?}
                         */
                        function (entityObject) {
                            if (entityObject.attributes.nid == nid) {
                                entity = entityObject;
                            }
                        }));
                    }
                }));
                if (entity) {
                    return [2 /*return*/, { data: entity }];
                }
                else {
                }
                return [2 /*return*/];
            });
        });
    };
    return DrupalApi;
}(BaseApi));
export { DrupalApi };
if (false) {
    /** @type {?} */
    DrupalApi.prototype.cache;
    /** @type {?} */
    DrupalApi.prototype.collections;
    /** @type {?} */
    DrupalApi.prototype.entities;
    /** @type {?} */
    DrupalApi.prototype.language;
    /** @type {?} */
    DrupalApi.prototype.nodes;
    /** @type {?} */
    DrupalApi.prototype.resources;
    /** @type {?} */
    DrupalApi.prototype.views;
    /* Skipping unhandled member: ;*/
}
//# sourceMappingURL=data:application/json;base64, 