"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var bluebird_1 = __importDefault(require("bluebird"));
var Helpers_1 = __importDefault(require("./Helpers"));
var deepmerge_1 = __importDefault(require("deepmerge"));
var helpers = new Helpers_1.default();
var UserData = /** @class */ (function () {
    function UserData(api, storage, userId) {
        this.api = api;
        this.storage = storage;
        this.userId = userId;
        this.recentsLimit = 10;
        this._data = {};
        this._favs = [];
        this._bookmarks = [];
        this._links = [];
        this._workspaces = [];
        this._storage = {
            recent_pages: [],
            page_settings: {},
            domains_pages_selected: [],
            domains_pages_pinned_selected: [],
            color_picker_colors: {},
            grid_state: {},
            panel_cards: [],
        };
        this._storagePrefix = "";
        this._storagePrefix = storage.user.prefix + "_data";
        var localstorage = storage.user.get(this._storagePrefix, {});
        this._storage = deepmerge_1.default(this._storage, localstorage);
        this._links = storage.user.get(this.META_RECENTS, []);
        if (this._links.length) {
            this._storage.recent_pages = this._links;
        }
        return;
    }
    Object.defineProperty(UserData.prototype, "META_HIDE_TUTORIAL", {
        get: function () {
            return "hide_tutorial";
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(UserData.prototype, "META_FAVS", {
        get: function () {
            return "shortcuts";
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(UserData.prototype, "META_BOOKMARKS", {
        get: function () {
            return "bookmarks";
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(UserData.prototype, "META_LOGO", {
        get: function () {
            return "logo";
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(UserData.prototype, "META_RECENTS", {
        get: function () {
            return "recents";
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(UserData.prototype, "META_WORKSPACES", {
        get: function () {
            return "workspaces";
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(UserData.prototype, "META_ACTIVE_WORKSPACE", {
        get: function () {
            return "active_workspace";
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(UserData.prototype, "favs", {
        get: function () {
            return this._favs;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(UserData.prototype, "bookmarks", {
        get: function () {
            return this._bookmarks;
        },
        enumerable: true,
        configurable: true
    });
    // convert key value from api data into object
    UserData.prototype.parse = function (data) {
        this._data = {};
        if (data === undefined) {
            return;
        }
        var i;
        for (i = 0; i < data.length; i++) {
            this._data[data[i].key] = data[i].value;
        }
        this._favs = this.get(this.META_FAVS, [], true) || [];
        this.upgradeFavs();
        this._bookmarks = this.get(this.META_BOOKMARKS, [], true) || [];
        // this._links = this.storage.user.get(this.META_RECENTS, []);
        this._workspaces = this.get(this.META_WORKSPACES, [], true) || [];
        return this._data;
    };
    UserData.prototype.set = function (key, value, stringify) {
        this._data[key] = value;
        return this.api.saveUserMetaData({
            userId: this.userId,
            data: [{ key: key, value: stringify ? JSON.stringify(value) : value }],
        });
    };
    UserData.prototype.refresh = function () {
        var _this = this;
        return this.api
            .getUserMetaData({
            userId: this.userId,
        })
            .then(function (response) {
            return _this.parse(response.data);
        });
    };
    UserData.prototype.get = function (key, defaultValue, parse) {
        if (key) {
            if (this._data.hasOwnProperty(key)) {
                try {
                    return parse ? JSON.parse(this._data[key]) : this._data[key];
                }
                catch (e) {
                    return this._data[key];
                }
            }
            return defaultValue || null;
        }
        return this._data;
    };
    UserData.prototype.destroy = function () {
        this._data = {};
    };
    UserData.prototype.getRecents = function () {
        this._links = this.storage.user.get(this.META_RECENTS, []);
        return this._links;
    };
    UserData.prototype.updateRecent = function (data) {
        var _this = this;
        this._links.forEach(function (ln, index) {
            if (ln.link != data.link)
                return;
            _this._links[index] = data;
        });
        this.saveRecents();
    };
    UserData.prototype.addRecent = function (data) {
        var _this = this;
        this._links.forEach(function (ln, index) {
            if (ln.link == data.link) {
                _this._links.splice(index, 1);
            }
        });
        this._links.splice(0, 0, data);
        if (this._links.length > this.recentsLimit) {
            this._links.pop();
        }
        this.saveRecents();
    };
    UserData.prototype.getRecent = function (folderId, pageId) {
        var link = this.getFavLink(folderId, pageId);
        return this._links.find(function (f) {
            return f.link == link;
        });
    };
    UserData.prototype.removeRecent = function (data) {
        var index = this._links.findIndex(function (f) {
            return f.link == data.link;
        });
        if (index > -1)
            this._links.splice(index, 1);
        // this._links.forEach((ln, index) => {
        //   if (ln.link == data.link) {
        //     this._links.splice(index, 1);
        //   }
        // });
        // this._links.splice(0, 0, data);
        // if (this._links.length > this.recentsLimit) {
        //   this._links.pop();
        // }
        this.saveRecents();
    };
    UserData.prototype.getFavs = function () {
        var _this = this;
        var p = new bluebird_1.default(function (resolve, reject) {
            _this.refresh()
                .then(function () {
                resolve(_this._favs);
            })
                .catch(reject);
        });
        return p;
    };
    UserData.prototype.updateFav = function (data) {
        var _this = this;
        var p = new bluebird_1.default(function (resolve, reject) {
            _this.refresh()
                .then(function () {
                var index = -1;
                for (var i = 0; i < _this._favs.length; i++) {
                    if (_this._favs[i].id !== data.id)
                        continue;
                    index = i;
                    _this._favs[i] = data;
                }
                if (index < 0) {
                    resolve({ message: "Favourite does not exist", favs: _this._favs });
                    return;
                }
                _this.set(_this.META_FAVS, _this._favs, true)
                    .then(function () {
                    resolve({
                        message: "Favourite has been updated",
                        favs: _this._favs,
                    });
                })
                    .catch(reject);
            })
                .catch(reject);
        });
        return p;
    };
    UserData.prototype.setFavName = function (folderId, pageId, title, folder) {
        var link = this.getFavLink(folderId, pageId);
        var index = -1;
        for (var i = 0; i < this._favs.length; i++) {
            if (this._favs[i].link !== link)
                continue;
            index = i;
        }
        if (index < 0 ||
            (this._favs[index].title == title && this._favs[index].folder == folder)) {
            return false;
        }
        this._favs[index].title = title;
        this._favs[index].folderId = folderId;
        this._favs[index].pageId = pageId;
        if (folder)
            this._favs[index].folder = folder;
        return true;
    };
    UserData.prototype.saveFavs = function () {
        var _this = this;
        var p = new bluebird_1.default(function (resolve, reject) {
            _this.set(_this.META_FAVS, _this._favs, true)
                .then(function () {
                resolve({ message: "Favourites has been updated", favs: _this._favs });
            })
                .catch(reject);
        });
        return p;
    };
    UserData.prototype.addFav = function (data) {
        var _this = this;
        var p = new bluebird_1.default(function (resolve, reject) {
            _this.refresh()
                .then(function () {
                // if (!this.checkForFavDuplicate(data.link)) {
                data.id = helpers.getUuid();
                _this._favs.push(data);
                _this.upgradeFavs();
                _this.set(_this.META_FAVS, _this._favs, true)
                    .then(function () {
                    resolve({
                        message: "Favourite has been saved",
                        favs: _this._favs,
                    });
                })
                    .catch(reject);
                // } else {
                //   resolve({ message: "Favourite already exists", favs: this._favs });
                // }
            })
                .catch(reject);
        });
        return p;
    };
    UserData.prototype.removeFav = function (data) {
        var _this = this;
        var p = new bluebird_1.default(function (resolve, reject) {
            _this.refresh()
                .then(function () {
                var index = -1;
                for (var i = 0; i < _this._favs.length; i++) {
                    if (_this._favs[i].id === data.id) {
                        _this._favs.splice(i, 1);
                        index = i;
                        break;
                    }
                }
                if (index < 0) {
                    resolve({ message: "Favourite already removed", favs: _this._favs });
                    return;
                }
                _this.set(_this.META_FAVS, _this._favs, true)
                    .then(function () {
                    resolve({
                        message: "Favourite has been removed",
                        favs: _this._favs,
                    });
                })
                    .catch(reject);
            })
                .catch(reject);
        });
        return p;
    };
    UserData.prototype.toggleFav = function (data) {
        if (this.checkForFavDuplicate(data.link)) {
            return this.removeFav(data);
        }
        else {
            return this.addFav(data);
        }
    };
    UserData.prototype.getFav = function (folderId, pageId) {
        var link = this.getFavLink(folderId, pageId);
        return this._favs.find(function (f) {
            return f.link == link;
        });
    };
    UserData.prototype.getFavLink = function (folderId, pageId) {
        return "/domains/" + folderId + "/pages/" + pageId;
    };
    UserData.prototype.isFav = function (folderId, pageId) {
        return this.checkForFavDuplicate(this.getFavLink(folderId, pageId));
    };
    UserData.prototype.saveWorkspaces = function (workspaces) {
        var _this = this;
        var p = new bluebird_1.default(function (resolve, reject) {
            _this.refresh()
                .then(function () {
                _this.set(_this.META_WORKSPACES, workspaces, true)
                    .then(function () {
                    resolve({
                        message: "Workspaces saved",
                        workspaces: _this._workspaces,
                    });
                })
                    .catch(reject);
            })
                .catch(reject);
        });
        return p;
    };
    UserData.prototype.getNewWorkspace = function () {
        return {
            name: "Workspace",
            boards: [],
            freeze: false,
            id: helpers.getUuid(),
            unit: "%",
        };
    };
    UserData.prototype.getWorkspaces = function () {
        var _this = this;
        var p = new bluebird_1.default(function (resolve, reject) {
            _this.refresh()
                .then(function () {
                resolve(_this._workspaces);
            })
                .catch(reject);
        });
        return p;
    };
    UserData.prototype.addWorkspace = function (data) {
        var _this = this;
        var p = new bluebird_1.default(function (resolve, reject) {
            _this.refresh()
                .then(function () {
                _this._workspaces.push(data);
                _this.set(_this.META_WORKSPACES, _this._workspaces, true)
                    .then(function () {
                    resolve({
                        message: "Workspace has been added",
                        workspaces: _this._workspaces,
                    });
                })
                    .catch(reject);
            })
                .catch(reject);
        });
        return p;
    };
    UserData.prototype.removeWorkspace = function (id) {
        var _this = this;
        var p = new bluebird_1.default(function (resolve, reject) {
            _this.refresh()
                .then(function () {
                var index = -1;
                for (var i = 0; i < _this._workspaces.length; i++) {
                    if (_this._workspaces[i].id === id) {
                        _this._workspaces.splice(i, 1);
                        index = i;
                        break;
                    }
                }
                if (index < 0) {
                    resolve({
                        message: "Workspace already removed",
                        workspaces: _this._workspaces,
                    });
                    return;
                }
                _this.set(_this.META_WORKSPACES, _this._workspaces, true)
                    .then(function () {
                    resolve({
                        message: "Workspace has been removed",
                        workspaces: _this._workspaces,
                    });
                })
                    .catch(reject);
            })
                .catch(reject);
        });
        return p;
    };
    UserData.prototype.setWorkspaces = function (data) {
        return this.set(this.META_WORKSPACES, JSON.stringify(data));
    };
    // public createBookmark(): IUserDataBookmark {
    //   return {
    //     title: '',
    //     folder: '',
    //     page: '',
    //     state: null,
    //     type: 0
    //   }
    // }
    UserData.prototype.getBookmarks = function () {
        var _this = this;
        var p = new bluebird_1.default(function (resolve, reject) {
            _this.refresh()
                .then(function () {
                resolve(_this._bookmarks);
            })
                .catch(reject);
        });
        return p;
    };
    UserData.prototype.addBookmark = function (bookmark) {
        var _this = this;
        var p = new bluebird_1.default(function (resolve, reject) {
            // this.refresh()
            //   .then(() => {
            _this._bookmarks.push(bookmark);
            _this.set(_this.META_BOOKMARKS, _this._bookmarks, true)
                .then(function () {
                resolve({
                    message: "Favourite has been saved",
                    bookmarks: _this._bookmarks,
                });
            })
                .catch(reject);
            // })
            // .catch(reject);
        });
        return p;
    };
    UserData.prototype.removeBookmark = function (index) {
        this._bookmarks.splice(index, 1);
        return this.saveBookmarks();
    };
    UserData.prototype.saveBookmarks = function () {
        var _this = this;
        var p = new bluebird_1.default(function (resolve, reject) {
            _this.set(_this.META_BOOKMARKS, _this._bookmarks, true)
                .then(function () {
                resolve({
                    message: "Favourites has been updated",
                    bookmarks: _this._bookmarks,
                });
            })
                .catch(reject);
        });
        return p;
    };
    UserData.prototype.getData = function (key) {
        return this._storage;
    };
    UserData.prototype.checkForFavDuplicate = function (link) {
        var index = -1;
        for (var i = 0; i < this._favs.length; i++) {
            if (this._favs[i].link === link) {
                index = 1;
                break;
            }
        }
        return index >= 0;
    };
    UserData.prototype.upgradeFavs = function () {
        var _this = this;
        var _loop_1 = function (i) {
            if (this_1._favs[i].id === undefined) {
                this_1._favs[i].id = helpers.getUuid();
            }
            ["pinned"].forEach(function (key) {
                if (_this._favs[i][key] === undefined)
                    _this._favs[i][key] = false;
            });
            ["pinnedOrder"].forEach(function (key) {
                if (_this._favs[i][key] === undefined)
                    _this._favs[i][key] = 0;
            });
            ["pinnedColor", "view", "customTitle"].forEach(function (key) {
                if (_this._favs[i][key] === undefined)
                    _this._favs[i][key] = "";
            });
            if (this_1._favs[i].pageId)
                return "continue";
            var domainPage = this_1._favs[i].link.split("/");
            this_1._favs[i].folderId = parseInt(domainPage[2]);
            this_1._favs[i].pageId = parseInt(domainPage[4]);
        };
        var this_1 = this;
        for (var i = 0; i < this._favs.length; i++) {
            _loop_1(i);
        }
    };
    UserData.prototype.saveRecents = function () {
        this.storage.user.save(this.META_RECENTS, JSON.stringify(this._links));
    };
    UserData.prototype.saveData = function () {
        this.storage.user.save(this._storagePrefix, JSON.stringify(this._storage));
    };
    return UserData;
}());
exports.default = UserData;
//# sourceMappingURL=UserData.js.map