"use strict";
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    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) : adopt(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 (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, 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 };
    }
};
var __read = (this && this.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};
Object.defineProperty(exports, "__esModule", { value: true });
var lodash_1 = require("lodash");
var BringgDashboardSDK_1 = require("./BringgDashboardSDK");
var data_entity_1 = require("./data-entity");
var StorableDataService = /** @class */ (function () {
    function StorableDataService(dataStore, mapper, extraDataStores) {
        var _this = this;
        this.dataStore = dataStore;
        this.extraDataStores = extraDataStores || [];
        this.mapper = mapper || (function (item) { return ({ current: item, diff: _this.dataStore.get(item.id) }); });
    }
    StorableDataService.prototype.loadAll = function (action, loadFunc, options) {
        return __awaiter(this, void 0, void 0, function () {
            var unloadedItems, shouldLoad, groupValue, loadFnIdsParams, items, mappedItems_1;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        options = (0, lodash_1.defaults)(options, data_entity_1.DEFAULT_OPTIONS);
                        unloadedItems = [];
                        shouldLoad = false;
                        if (Array.isArray(options.groupValue)) {
                            unloadedItems = options.groupValue.filter(function (value) { return !_this.dataStore.isGroupInitialized(options.groupType, value); });
                            shouldLoad = unloadedItems.length > 0;
                            groupValue = unloadedItems;
                        }
                        else {
                            // The same storable-data-service method is used for loadAll group key in this case is undefined-undefined
                            shouldLoad = !this.dataStore.isGroupInitialized(options.groupType, options.groupValue);
                            groupValue = options.groupValue;
                        }
                        if (!(!options.useCache || shouldLoad)) return [3 /*break*/, 2];
                        loadFnIdsParams = groupValue;
                        if (!options.useCache) {
                            loadFnIdsParams = options.groupValue;
                        }
                        return [4 /*yield*/, loadFunc(loadFnIdsParams)];
                    case 1:
                        items = _a.sent();
                        mappedItems_1 = items.map(function (item) { return _this.mapper(item, { action: action }); });
                        if (options.groupType) {
                            this.dataStore.setGroup(options.groupType, groupValue, mappedItems_1);
                        }
                        else {
                            this.dataStore.setAll(mappedItems_1);
                        }
                        this.extraDataStores.forEach(function (dataStore) { return dataStore.setMany(mappedItems_1, options.fields); });
                        _a.label = 2;
                    case 2: return [2 /*return*/, options.groupType
                            ? this.dataStore.getGroup(options.groupType, options.groupValue)
                            : this.dataStore.getAll()];
                }
            });
        });
    };
    StorableDataService.prototype.loadMany = function (action, loadFunc, ids, options) {
        return __awaiter(this, void 0, void 0, function () {
            var unloadedIds, clientItems;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        options = (0, lodash_1.defaults)(options, data_entity_1.DEFAULT_OPTIONS);
                        if (!options.useCache) {
                            return [2 /*return*/, this.loadInChunks(ids, loadFunc, action, options)];
                        }
                        unloadedIds = ids.filter(function (id) {
                            var item = _this.dataStore.get(id);
                            if (!item) {
                                return true;
                            }
                            return _this.extraDataStores.some(function (dataStore) { return !dataStore.has(item, options.fields); });
                        });
                        if (!(ids.length === 0 || unloadedIds.length > 0)) return [3 /*break*/, 2];
                        return [4 /*yield*/, this.loadInChunks(unloadedIds, loadFunc, action, options)];
                    case 1:
                        clientItems = _a.sent();
                        if (ids.length === 0) {
                            return [2 /*return*/, clientItems];
                        }
                        _a.label = 2;
                    case 2: return [2 /*return*/, ids.map(function (id) { return _this.dataStore.get(id); }).filter(Boolean)];
                }
            });
        });
    };
    StorableDataService.prototype.loadInChunks = function (idsToLoad, loadFunc, action, options) {
        var _a;
        return __awaiter(this, void 0, void 0, function () {
            var allClientItems, items, clientItems, chunkSize, i, chunkIds, items, clientItems;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        allClientItems = [];
                        if (!(idsToLoad.length === 0)) return [3 /*break*/, 2];
                        return [4 /*yield*/, loadFunc([])];
                    case 1:
                        items = _b.sent();
                        clientItems = this.updateManyInStores(items, action, options.fields);
                        allClientItems.push.apply(allClientItems, __spreadArray([], __read(clientItems), false));
                        return [3 /*break*/, 6];
                    case 2:
                        chunkSize = options.chunkSize || idsToLoad.length;
                        i = 0;
                        _b.label = 3;
                    case 3:
                        if (!(i < idsToLoad.length)) return [3 /*break*/, 6];
                        if ((_a = options === null || options === void 0 ? void 0 : options.signal) === null || _a === void 0 ? void 0 : _a.aborted) {
                            throw new Error('Operation was aborted');
                        }
                        chunkIds = idsToLoad.slice(i, i + chunkSize);
                        return [4 /*yield*/, loadFunc(chunkIds)];
                    case 4:
                        items = _b.sent();
                        clientItems = this.updateManyInStores(items, action, options.fields);
                        allClientItems.push.apply(allClientItems, __spreadArray([], __read(clientItems), false));
                        _b.label = 5;
                    case 5:
                        i += chunkSize;
                        return [3 /*break*/, 3];
                    case 6: return [2 /*return*/, allClientItems.map(function (mappedItems) { return mappedItems.current; })];
                }
            });
        });
    };
    StorableDataService.prototype.load = function (action, loadFunc, id, options) {
        return __awaiter(this, void 0, void 0, function () {
            var item;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        options = (0, lodash_1.defaults)(options, data_entity_1.DEFAULT_OPTIONS);
                        if (!(!options.useCache || !this.dataStore.get(id))) return [3 /*break*/, 2];
                        return [4 /*yield*/, loadFunc()];
                    case 1:
                        item = _a.sent();
                        this.updateInStores(item, action);
                        _a.label = 2;
                    case 2: return [2 /*return*/, this.dataStore.get(id)];
                }
            });
        });
    };
    StorableDataService.prototype.modify = function (action, updateFunc, onUpdate) {
        return __awaiter(this, void 0, void 0, function () {
            var item, modifiedItems;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, updateFunc()];
                    case 1:
                        item = _a.sent();
                        modifiedItems = this.updateInStores(item, action);
                        onUpdate === null || onUpdate === void 0 ? void 0 : onUpdate(modifiedItems);
                        return [2 /*return*/, modifiedItems.current];
                }
            });
        });
    };
    StorableDataService.prototype.modifyMany = function (action, updateFunc, fields, onUpdate) {
        return __awaiter(this, void 0, void 0, function () {
            var items, modifiedItems;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, updateFunc()];
                    case 1:
                        items = _a.sent();
                        modifiedItems = this.updateManyInStores(items, action, fields);
                        onUpdate === null || onUpdate === void 0 ? void 0 : onUpdate(modifiedItems);
                        return [2 /*return*/, modifiedItems.map(function (mappedItems) { return mappedItems.current; })];
                }
            });
        });
    };
    StorableDataService.prototype.delete = function (action, deleteFunc, id) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, deleteFunc()];
                    case 1:
                        _a.sent();
                        return [2 /*return*/, this.removeFromStores(id)];
                }
            });
        });
    };
    StorableDataService.prototype.deleteMany = function (action, deleteFunc, ids) {
        return __awaiter(this, void 0, void 0, function () {
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, deleteFunc()];
                    case 1:
                        _a.sent();
                        return [2 /*return*/, (0, BringgDashboardSDK_1.getGlobals)().mobx.runInAction(function () {
                                return ids.map(function (id) { return _this.removeFromStores(id); });
                            })];
                }
            });
        });
    };
    StorableDataService.prototype.mapItem = function (item, extraMapperParams) {
        return this.mapper(item, __assign({}, extraMapperParams));
    };
    StorableDataService.prototype.updateInStores = function (item, action, fields, extraMapperParams) {
        return this.updateManyInStores([item], action, fields, extraMapperParams)[0];
    };
    StorableDataService.prototype.updateManyInStores = function (items, action, fields, extraMapperParams) {
        var _this = this;
        return (0, BringgDashboardSDK_1.getGlobals)().mobx.runInAction(function () {
            var clientItems = items.map(function (item) { return _this.mapper(item, __assign({ action: action }, extraMapperParams)); });
            _this.dataStore.setMany(clientItems);
            _this.extraDataStores.forEach(function (dataStore) { return dataStore.setMany(clientItems, fields); });
            return clientItems;
        });
    };
    StorableDataService.prototype.removeFromStores = function (id) {
        var item = this.dataStore.get(id);
        this.dataStore.remove(id);
        this.extraDataStores.forEach(function (dataStore) { return dataStore.remove(id); });
        return item;
    };
    StorableDataService.prototype.getFromStores = function (ids, fields) {
        var _this = this;
        return ids
            .map(function (id) {
            var item = _this.dataStore.get(id);
            return item && (!fields || _this.extraDataStores.every(function (dataStore) { return dataStore.has(item, fields); }))
                ? item
                : undefined;
        })
            .filter(Boolean);
    };
    return StorableDataService;
}());
exports.default = StorableDataService;
//# sourceMappingURL=storable-data-service.js.map