"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var igd_core_1 = require("@intelligentgraphics/igd.core");
var Logger_1 = require("../Logger");
var CatalogManager_1 = require("../CatalogManager");
/**
 * IGXACatalogManager is an implementation of the ICatalogManager interface that
 * uses the IGD.IGXA catalog format as data source.
 */
var IGXACatalogManager = /** @class */ (function (_super) {
    tslib_1.__extends(IGXACatalogManager, _super);
    function IGXACatalogManager(settings) {
        var _this = _super.call(this) || this;
        _this.lastID = 0;
        _this._settings = settings;
        _this.patchData(settings.data);
        _this.cache.parseIGXA(settings.data);
        _this._image = _this._settings.data.Image;
        _this._title = _this._settings.data.Title;
        return _this;
    }
    IGXACatalogManager.Create = function (settings) {
        var tCatalogManager = new IGXACatalogManager(settings);
        return Promise.resolve(tCatalogManager);
    };
    /** Returns the class name for identifying instances at runtime */
    IGXACatalogManager.prototype.getClassName = function () {
        return "IGXACatalogManager";
    };
    /**
     * Retrieves the addables of an item.
     *
     * @param {string} baseArticleId number of the base article for which addables should be searched.
     * @returns {Promise<IGXA.IArticleItem[]>}
     * @memberof IGXACatalogManager
     */
    IGXACatalogManager.prototype.getAddables = function (baseArticleId) {
        var _this = this;
        var tBaseItem = this.findArticleItem(baseArticleId);
        var tItems = [];
        if (tBaseItem && tBaseItem.Addables) {
            tBaseItem.Addables.forEach(function (add) {
                var tAddItem = _this.findArticleItem(add);
                if (tAddItem) {
                    tItems.push(tAddItem);
                }
            });
        }
        return Promise.resolve(tItems);
    };
    // IGXA-specific methods
    IGXACatalogManager.prototype.hasFolder = function (folderId) {
        return (this.findFolderItem(this.Settings.data.Items, folderId) !==
            undefined);
    };
    IGXACatalogManager.prototype.removeFolder = function (folderId) {
        function processLevel(items) {
            var tIdx = -1;
            if (items.some(function (item, idx) {
                if (item.Type === igd_core_1.IGXA.EItemType.Folder) {
                    var tFI = item;
                    if (tFI.ID === folderId) {
                        tIdx = idx;
                        return true;
                    }
                    else {
                        return processLevel(tFI.SubItems || []);
                    }
                }
                return false;
            })) {
                if (tIdx > -1) {
                    items.splice(tIdx, 1);
                }
                return true;
            }
            else {
                return false;
            }
        }
        return processLevel(this.Settings.data.Items);
    };
    IGXACatalogManager.prototype.removeArticle = function (articleId, parentFolderId) {
        var tParentSet;
        if (parentFolderId) {
            var tFI = this.findFolderItem(this.Settings.data.Items, parentFolderId);
            if (tFI) {
                tParentSet = tFI.SubItems || [];
            }
        }
        else {
            tParentSet = this.Settings.data.Items;
        }
        if (tParentSet === undefined) {
            Logger_1.default.warn("IGXACatalogManager.removeArticle()", "Could not find specified parent folder.");
            return;
        }
        var itemIndex = tParentSet.findIndex(function (item) {
            return (item.Type === igd_core_1.IGXA.EItemType.ArticleCom ||
                item.Type === igd_core_1.IGXA.EItemType.ArticleGfx) &&
                item.ID === articleId;
        });
        if (itemIndex > -1) {
            tParentSet.splice(itemIndex, 1);
        }
    };
    IGXACatalogManager.prototype.addFolder = function (newFolderItem, parentFolderId) {
        if (newFolderItem.ID) {
            if (this.findFolderItem(this.Settings.data.Items, newFolderItem.ID) !== undefined) {
                // folder with this id already exists
                return true;
            }
        }
        else {
            newFolderItem.ID = (++this.lastID).toString();
        }
        var tParentSet;
        if (parentFolderId) {
            var tFI = this.findFolderItem(this.Settings.data.Items, parentFolderId);
            if (tFI) {
                tParentSet = tFI.SubItems || [];
            }
        }
        else {
            tParentSet = this.Settings.data.Items;
        }
        if (tParentSet) {
            tParentSet.push(newFolderItem);
        }
        else {
            Logger_1.default.error("IGXACatalogManager.addFolder()", "Could not find specified parent folder.");
            return false;
        }
        return true;
    };
    IGXACatalogManager.prototype.addArticle = function (newArticleItem, parentFolderId) {
        var tParentSet;
        if (parentFolderId) {
            var tFI = this.findFolderItem(this.Settings.data.Items, parentFolderId);
            if (tFI) {
                tParentSet = tFI.SubItems || [];
            }
        }
        else {
            tParentSet = this.Settings.data.Items;
        }
        if (tParentSet) {
            tParentSet.push(newArticleItem);
        }
        else {
            Logger_1.default.error("IGXACatalogManager.addArticle()", "Could not find specified parent folder.");
            return false;
        }
        return true;
    };
    IGXACatalogManager.prototype.addItems = function (items, parentFolderId) {
        var tParentSet;
        if (parentFolderId) {
            var tFI = this.findFolderItem(this.Settings.data.Items, parentFolderId);
            if (tFI) {
                tParentSet = tFI.SubItems || [];
            }
        }
        else {
            tParentSet = this.Settings.data.Items;
        }
        if (tParentSet) {
            items.forEach(function (item) {
                tParentSet.push(item);
            });
        }
        else {
            Logger_1.default.error("IGXACatalogManager.addArticle()", "Could not find specified parent folder.");
            return false;
        }
        return true;
    };
    /** Retrieves the folder item. Synchroneous version of getFolder().
     * @param folderId Internal ID of the folder.
     * @returns The folder item
     */
    IGXACatalogManager.prototype.getIGXAFolder = function (folderId) {
        return this.cache.getItemById(folderId);
    };
    /** Retrieves the first article item with given id.
     * @param articleId article id.
     * @returns The article item
     */
    IGXACatalogManager.prototype.getIGXAArticle = function (articleId) {
        return this.cache.getItemById(articleId);
    };
    IGXACatalogManager.prototype.getIGXASet = function (setId) {
        return this.cache.getItemById(setId);
    };
    /** Retrieves the parent folder item.
     * @param folderId Internal ID of the folder.
     * @returns The parent folder item as Promise
     */
    IGXACatalogManager.prototype.getIGXAParentFolder = function (folderId) {
        function checkLevel(parentId, items) {
            var tR;
            items.some(function (item) {
                if (item.Type === igd_core_1.IGXA.EItemType.Folder ||
                    item.Type === igd_core_1.IGXA.EItemType.MultiArticle) {
                    var tFI = item;
                    if (tFI.ID === folderId) {
                        tR = parentId;
                        return true;
                    }
                    else {
                        tR = checkLevel(tFI.ID, tFI.SubItems || []);
                        return tR !== undefined;
                    }
                }
                return false;
            });
            return tR;
        }
        var tR = checkLevel(undefined, this.Settings.data.Items);
        if (tR === undefined) {
            return undefined;
        }
        else {
            return this.findFolderItem(this.Settings.data.Items, tR);
        }
    };
    Object.defineProperty(IGXACatalogManager.prototype, "IGXA", {
        get: function () {
            return this.Settings.data;
        },
        enumerable: true,
        configurable: true
    });
    // PRIVATE HELPERS:
    IGXACatalogManager.prototype.getCatalogTextLocalized = function (text) {
        var tR;
        switch (typeof text) {
            case "string":
                tR = text;
                break;
            case "object":
                if (text.hasOwnProperty("length")) {
                    tR = text;
                }
                else if (text.hasOwnProperty(this.Settings.catalogLocale)) {
                    tR = this.getCatalogTextLocalized(text[this.Settings.catalogLocale]);
                }
                else {
                    tR = "";
                }
                break;
            default:
                tR = "";
        }
        return tR;
    };
    IGXACatalogManager.prototype.findFolderItem = function (root, id) {
        var _this = this;
        var tR;
        root.some(function (item) {
            if (item.Type === igd_core_1.IGXA.EItemType.Folder ||
                item.Type === igd_core_1.IGXA.EItemType.MultiArticle) {
                var tFI = item;
                if (tFI.ID === id) {
                    tR = tFI;
                    return true;
                }
                else {
                    tR = _this.findFolderItem(tFI.SubItems || [], id);
                    return tR !== undefined;
                }
            }
            return false;
        });
        return tR;
    };
    IGXACatalogManager.prototype.patchData = function (data) {
        var _this = this;
        var idPatchFields = [
            "FolderID",
            "ArticleID",
            "ImpressionID",
        ];
        var recurse = function (items) {
            var e_1, _a;
            if (!items) {
                return;
            }
            var _loop_1 = function (entry) {
                var field = idPatchFields.find(function (key) { return entry[key] !== undefined; });
                // patch old ids (FolderID, ArticleID) to ID
                if (field) {
                    entry.ID = entry[field];
                    delete entry[field];
                }
                // fix type property
                if (typeof entry.Type === "string") {
                    entry.Type = igd_core_1.IGXA.EItemType[entry.Type];
                }
                // fix visibility
                if (entry.Type === igd_core_1.IGXA.EItemType.ArticleCom ||
                    entry.Type === igd_core_1.IGXA.EItemType.ArticleGfx) {
                    if (entry.Visibility === undefined) {
                        entry.Visibility = igd_core_1.IGXA.EItemVisibility.Always;
                    }
                    else if (typeof entry.Visibility === "string") {
                        entry.Visibility =
                            igd_core_1.IGXA.EItemVisibility[entry.Visibility];
                    }
                }
                if (!entry["Source"] &&
                    (entry.Type === igd_core_1.IGXA.EItemType.ArticleCom ||
                        entry.Type === igd_core_1.IGXA.EItemType.ArticleGfx ||
                        entry.Type === igd_core_1.IGXA.EItemType.Impression ||
                        entry.Type === igd_core_1.IGXA.EItemType.Set)) {
                    entry.Source = _this.Settings.sourceId;
                }
                // add ids if they're missing
                if (entry.Type === igd_core_1.IGXA.EItemType.Folder ||
                    entry.Type === igd_core_1.IGXA.EItemType.MultiArticle) {
                    if (!entry.ID) {
                        entry.ID = (++_this.lastID).toString();
                    }
                }
                if ("SubItems" in entry) {
                    recurse(entry.SubItems);
                }
            };
            try {
                for (var items_1 = tslib_1.__values(items), items_1_1 = items_1.next(); !items_1_1.done; items_1_1 = items_1.next()) {
                    var entry = items_1_1.value;
                    _loop_1(entry);
                }
            }
            catch (e_1_1) { e_1 = { error: e_1_1 }; }
            finally {
                try {
                    if (items_1_1 && !items_1_1.done && (_a = items_1.return)) _a.call(items_1);
                }
                finally { if (e_1) throw e_1.error; }
            }
        };
        recurse(data.Items);
    };
    IGXACatalogManager.prototype.findArticleItem = function (baseArticleId) {
        var tR;
        function processFolder(items) {
            return items.some(function (item) {
                if (item.Type === igd_core_1.IGXA.EItemType.Folder ||
                    item.Type === igd_core_1.IGXA.EItemType.MultiArticle) {
                    return processFolder(item.SubItems || []);
                }
                else {
                    if (item.ID === baseArticleId) {
                        tR = item;
                        return true;
                    }
                }
                return false;
            });
        }
        processFolder(this.Settings.data.Items);
        return tR;
    };
    Object.defineProperty(IGXACatalogManager.prototype, "Settings", {
        get: function () {
            return this._settings;
        },
        enumerable: true,
        configurable: true
    });
    return IGXACatalogManager;
}(CatalogManager_1.CatalogManager));
exports.IGXACatalogManager = IGXACatalogManager;
