"use strict";
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
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 __values = (this && this.__values) || function(o) {
    var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
    if (m) return m.call(o);
    if (o && typeof o.length === "number") return {
        next: function () {
            if (o && i >= o.length) o = void 0;
            return { value: o && o[i++], done: !o };
        }
    };
    throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
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));
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.MAX_CONCURRENT_CHUNKED_REQUESTS = exports.DEFAULT_CHUNK_SIZE = void 0;
var types_1 = require("@bringg/types");
var chunk_1 = __importDefault(require("lodash/chunk"));
var forEach_1 = __importDefault(require("lodash/forEach"));
var last_1 = __importDefault(require("lodash/last"));
var rxjs_1 = require("rxjs");
var operators_1 = require("rxjs/operators");
var BaseStore_1 = __importDefault(require("../../Core/BaseStore"));
var UsersService_1 = __importDefault(require("../Service/UsersService"));
var User_consts_1 = require("../User.consts");
var UserHelpers_1 = require("../UserHelpers");
var THROTTLE_TIME = 500;
var MIN_INTERVAL_BETWEEN_CHUNKED_REQUESTS = 300;
exports.DEFAULT_CHUNK_SIZE = 50;
exports.MAX_CONCURRENT_CHUNKED_REQUESTS = 4;
var UsersStore = /** @class */ (function (_super) {
    __extends(UsersStore, _super);
    function UsersStore(session, throttleTimeValue) {
        var e_1, _a;
        var _this = _super.call(this, {
            realTime: {
                addItemsWhenHandlingUpdate: false
            }
        }) || this;
        _this.groupUpdateEvents = [];
        _this.groupedValues = new Map();
        _this.drivers = [];
        _this.fetchedStatus = {
            drivers: false,
            customers: false,
            adminsAndDispatchers: false
        };
        _this.usersService = new UsersService_1.default(session, _this);
        _this.onlineDriversCounterByTeam = new Map();
        try {
            for (var _b = __values(Object.keys(User_consts_1.GROUP_VALUES)), _c = _b.next(); !_c.done; _c = _b.next()) {
                var groupId = _c.value;
                _this.groupedValues.set(User_consts_1.GROUP_VALUES[groupId], new Set());
            }
        }
        catch (e_1_1) { e_1 = { error: e_1_1 }; }
        finally {
            try {
                if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
            }
            finally { if (e_1) throw e_1.error; }
        }
        throttleTimeValue = throttleTimeValue || THROTTLE_TIME;
        _this.onItemRemoved(function (userId, user) {
            var e_2, _a;
            var isDriverOnline = (user === null || user === void 0 ? void 0 : user.status) === types_1.Connection.Online;
            if (isDriverOnline && user.team_ids) {
                try {
                    for (var _b = __values(user.team_ids), _c = _b.next(); !_c.done; _c = _b.next()) {
                        var teamId = _c.value;
                        _this.onlineDriversCounterByTeam.set(teamId, Math.max(_this.onlineDriversCounterByTeam.get(teamId) - 1, 0));
                    }
                }
                catch (e_2_1) { e_2 = { error: e_2_1 }; }
                finally {
                    try {
                        if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
                    }
                    finally { if (e_2) throw e_2.error; }
                }
            }
        });
        //group by and save ids | can add config to throttle through users( maybe increase if admin )
        _this.state$
            .pipe((0, operators_1.throttleTime)(throttleTimeValue, rxjs_1.asyncScheduler, { trailing: true, leading: false }))
            .subscribe(function (users) {
            _this.initGroups(users.values());
            _this.emitGroupEvents();
        });
        return _this;
    }
    UsersStore.prototype.getRelevantDrivers = function (groupsToInit) {
        if (groupsToInit.length === Object.keys(User_consts_1.GROUP_VALUES).length) {
            return [];
        }
        else {
            return this.drivers.filter(function (driver) {
                return !((UserHelpers_1.UserHelpers.isOnlineDriver(driver) && groupsToInit.includes(User_consts_1.GROUP_VALUES.OnlineDrivers)) ||
                    (UserHelpers_1.UserHelpers.isOfflineDriver(driver) && groupsToInit.includes(User_consts_1.GROUP_VALUES.OfflineDrivers)) ||
                    (UserHelpers_1.UserHelpers.isOnShiftDriver(driver) && groupsToInit.includes(User_consts_1.GROUP_VALUES.OnShiftDrivers)) ||
                    (UserHelpers_1.UserHelpers.isAdmin(driver) && groupsToInit.includes(User_consts_1.GROUP_VALUES.Admins)) ||
                    (UserHelpers_1.UserHelpers.isDispatcher(driver) && groupsToInit.includes(User_consts_1.GROUP_VALUES.Dispatchers)) ||
                    (UserHelpers_1.UserHelpers.isCustomer(driver) && groupsToInit.includes(User_consts_1.GROUP_VALUES.Customers)));
            });
        }
    };
    UsersStore.prototype.initGroups = function (users, groupsToInit) {
        var e_3, _a, _b, e_4, _c, e_5, _d, e_6, _e, e_7, _f;
        if (groupsToInit === void 0) { groupsToInit = Object.keys(User_consts_1.GROUP_VALUES); }
        var groups = {};
        try {
            for (var groupsToInit_1 = __values(groupsToInit), groupsToInit_1_1 = groupsToInit_1.next(); !groupsToInit_1_1.done; groupsToInit_1_1 = groupsToInit_1.next()) {
                var groupId = groupsToInit_1_1.value;
                groups[groupId] = new Set();
            }
        }
        catch (e_3_1) { e_3 = { error: e_3_1 }; }
        finally {
            try {
                if (groupsToInit_1_1 && !groupsToInit_1_1.done && (_a = groupsToInit_1.return)) _a.call(groupsToInit_1);
            }
            finally { if (e_3) throw e_3.error; }
        }
        var relevantDrivers = this.getRelevantDrivers(groupsToInit);
        this.drivers.length = 0; // do not change drivers ref - manu pointer rely on it on their state on bringg-web
        (_b = this.drivers).push.apply(_b, __spreadArray([], __read(relevantDrivers), false));
        this.onlineDriversCounterByTeam = new Map();
        try {
            for (var users_1 = __values(users), users_1_1 = users_1.next(); !users_1_1.done; users_1_1 = users_1.next()) {
                var user = users_1_1.value;
                if (user.driver) {
                    this.drivers.push(user);
                    var isDriverOnline = user.status === types_1.Connection.Online;
                    if (isDriverOnline && user.team_ids) {
                        try {
                            for (var _g = (e_5 = void 0, __values(user.team_ids)), _h = _g.next(); !_h.done; _h = _g.next()) {
                                var teamId = _h.value;
                                this.onlineDriversCounterByTeam.set(teamId, this.onlineDriversCounterByTeam.has(teamId)
                                    ? this.onlineDriversCounterByTeam.get(teamId) + 1
                                    : 1);
                            }
                        }
                        catch (e_5_1) { e_5 = { error: e_5_1 }; }
                        finally {
                            try {
                                if (_h && !_h.done && (_d = _g.return)) _d.call(_g);
                            }
                            finally { if (e_5) throw e_5.error; }
                        }
                    }
                }
                var groupIds = (0, User_consts_1.userToGroupsMapper)(user);
                try {
                    for (var groupIds_1 = (e_6 = void 0, __values(groupIds)), groupIds_1_1 = groupIds_1.next(); !groupIds_1_1.done; groupIds_1_1 = groupIds_1.next()) {
                        var groupId = groupIds_1_1.value;
                        if (groups[groupId]) {
                            groups[groupId].add(user);
                        }
                    }
                }
                catch (e_6_1) { e_6 = { error: e_6_1 }; }
                finally {
                    try {
                        if (groupIds_1_1 && !groupIds_1_1.done && (_e = groupIds_1.return)) _e.call(groupIds_1);
                    }
                    finally { if (e_6) throw e_6.error; }
                }
            }
        }
        catch (e_4_1) { e_4 = { error: e_4_1 }; }
        finally {
            try {
                if (users_1_1 && !users_1_1.done && (_c = users_1.return)) _c.call(users_1);
            }
            finally { if (e_4) throw e_4.error; }
        }
        try {
            for (var groupsToInit_2 = __values(groupsToInit), groupsToInit_2_1 = groupsToInit_2.next(); !groupsToInit_2_1.done; groupsToInit_2_1 = groupsToInit_2.next()) {
                var groupId = groupsToInit_2_1.value;
                this.groupedValues.set(User_consts_1.GROUP_VALUES[groupId], groups[groupId] || new Set());
            }
        }
        catch (e_7_1) { e_7 = { error: e_7_1 }; }
        finally {
            try {
                if (groupsToInit_2_1 && !groupsToInit_2_1.done && (_f = groupsToInit_2.return)) _f.call(groupsToInit_2);
            }
            finally { if (e_7) throw e_7.error; }
        }
    };
    UsersStore.prototype.create = function (user) {
        return __awaiter(this, void 0, void 0, function () {
            var newUser;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.usersService.create(user)];
                    case 1:
                        newUser = _a.sent();
                        this.addToStore(newUser);
                        return [2 /*return*/, newUser];
                }
            });
        });
    };
    UsersStore.prototype.getDriversByTeam = function (teamId) {
        return __awaiter(this, void 0, void 0, function () {
            var users;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.usersService.getDriversByTeam(teamId)];
                    case 1:
                        users = _a.sent();
                        users.forEach(function (user) { return _this.addToStore(user); });
                        return [2 /*return*/, users];
                }
            });
        });
    };
    UsersStore.prototype.getAll = function (page, limit) {
        if (page === void 0) { page = 1; }
        if (limit === void 0) { limit = 50; }
        return __awaiter(this, void 0, void 0, function () {
            var response;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.usersService.getAll(page, limit)];
                    case 1:
                        response = _a.sent();
                        (0, forEach_1.default)(response.users, function (user) { return (_this.getItem(user.id) ? _this.updateInStore(user) : _this.addToStore(user)); });
                        return [2 /*return*/, response];
                }
            });
        });
    };
    UsersStore.prototype.getAllKeysetPagination = function (request) {
        return __awaiter(this, void 0, void 0, function () {
            var response;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.usersService.getAllKeysetPagination(request)];
                    case 1:
                        response = _a.sent();
                        (0, forEach_1.default)(response.users, function (user) { return (_this.getItem(user.id) ? _this.updateInStore(user) : _this.addToStore(user)); });
                        this.initGroups(this.getItems());
                        return [2 /*return*/, response];
                }
            });
        });
    };
    UsersStore.prototype.invite = function (userId) {
        return __awaiter(this, void 0, void 0, function () {
            var user;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.usersService.invite(userId)];
                    case 1:
                        user = _a.sent();
                        this.updateInStore(user);
                        return [2 /*return*/, user];
                }
            });
        });
    };
    UsersStore.prototype.inviteByEmail = function (userId) {
        return __awaiter(this, void 0, void 0, function () {
            var user;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.usersService.inviteByEmail(userId)];
                    case 1:
                        user = _a.sent();
                        this.updateInStore(user);
                        return [2 /*return*/, user];
                }
            });
        });
    };
    UsersStore.prototype.getAllAdminsAndDispatchers = function (request) {
        return __awaiter(this, void 0, void 0, function () {
            var _this = this;
            return __generator(this, function (_a) {
                return [2 /*return*/, this.getOrFetchUsers(request, this.fetchedStatus.adminsAndDispatchers, function (isAllAdminsAndDispatchersFetched) {
                        return (_this.fetchedStatus.adminsAndDispatchers = isAllAdminsAndDispatchersFetched);
                    }, function () {
                        var _a;
                        var args = [];
                        for (var _i = 0; _i < arguments.length; _i++) {
                            args[_i] = arguments[_i];
                        }
                        return (_a = _this.usersService).getAllAdminsAndDispatchers.apply(_a, __spreadArray([], __read(args), false));
                    }, function () { return _this.getAllLocalAdminsAndDispatchers(); })];
            });
        });
    };
    UsersStore.prototype.getAllDrivers = function (request) {
        return __awaiter(this, void 0, void 0, function () {
            var options, response, isOnlyCustomer, isOnlyOnlineDrivers, groups;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        options = request.options;
                        isOnlyCustomer = options === null || options === void 0 ? void 0 : options.onlyCustomers;
                        isOnlyOnlineDrivers = options === null || options === void 0 ? void 0 : options.onlyOnlineDriver;
                        if (!isOnlyCustomer) return [3 /*break*/, 2];
                        return [4 /*yield*/, this.getOrFetchUsers(request, this.fetchedStatus.customers, function (isAllCustomersFetched) { return (_this.fetchedStatus.customers = isAllCustomersFetched); }, this.usersService.getAllDrivers, function () { return _this.getCustomers(); })];
                    case 1:
                        response = _a.sent();
                        return [3 /*break*/, 4];
                    case 2: return [4 /*yield*/, this.getOrFetchUsers(request, this.fetchedStatus.drivers, function (isAllDriversFetched) { return (_this.fetchedStatus.drivers = isAllDriversFetched); }, function () {
                            var _a;
                            var args = [];
                            for (var _i = 0; _i < arguments.length; _i++) {
                                args[_i] = arguments[_i];
                            }
                            return (_a = _this.usersService).getAllDrivers.apply(_a, __spreadArray([], __read(args), false));
                        }, function () { return (isOnlyOnlineDrivers ? __spreadArray([], __read(_this.getOnlineDrivers()), false) : __spreadArray([], __read(_this.getAllLocalDrivers()), false)); })];
                    case 3:
                        response = _a.sent();
                        _a.label = 4;
                    case 4:
                        groups = isOnlyCustomer
                            ? [User_consts_1.GROUP_VALUES.Customers]
                            : isOnlyOnlineDrivers
                                ? [User_consts_1.GROUP_VALUES.OnlineDrivers]
                                : [User_consts_1.GROUP_VALUES.OfflineDrivers, User_consts_1.GROUP_VALUES.OnlineDrivers, User_consts_1.GROUP_VALUES.OnShiftDrivers];
                        this.initGroups(response.users, groups);
                        return [2 /*return*/, response];
                }
            });
        });
    };
    UsersStore.prototype.getOrFetchUsers = function (request, isFetchedFlag, setIsFetchedFlag, fetchUsers, getLocalUsers) {
        return __awaiter(this, void 0, void 0, function () {
            var response;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!!isFetchedFlag) return [3 /*break*/, 2];
                        return [4 /*yield*/, fetchUsers(request)];
                    case 1:
                        response = _a.sent();
                        response.users.forEach(function (driver) { return _this.addToStore(driver); });
                        if (!response.next_page_cursor && !response.previous_page_cursor) {
                            setIsFetchedFlag(true);
                        }
                        return [2 /*return*/, response];
                    case 2: return [2 /*return*/, {
                            next_page_cursor: null,
                            previous_page_cursor: null,
                            users: getLocalUsers()
                        }];
                }
            });
        });
    };
    UsersStore.prototype.byUserType = function (userTypeId) {
        return __awaiter(this, void 0, void 0, function () {
            var users;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.usersService.byUserType(userTypeId)];
                    case 1:
                        users = _a.sent();
                        users.forEach(function (user) { return _this.addToStore(user); });
                        return [2 /*return*/, users];
                }
            });
        });
    };
    UsersStore.prototype.makeAdmin = function (userId) {
        return __awaiter(this, void 0, void 0, function () {
            var user;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.usersService.makeAdmin(userId)];
                    case 1:
                        user = _a.sent();
                        this.updateInStore(user);
                        return [2 /*return*/, user];
                }
            });
        });
    };
    UsersStore.prototype.update = function (userId, userDelta) {
        return __awaiter(this, void 0, void 0, function () {
            var user;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.usersService.update(userId, userDelta)];
                    case 1:
                        user = _a.sent();
                        this.updateInStore(user);
                        return [2 /*return*/, user];
                }
            });
        });
    };
    UsersStore.prototype.delete = function (userId) {
        return __awaiter(this, void 0, void 0, function () {
            var success;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.usersService.delete(userId)];
                    case 1:
                        success = _a.sent();
                        if (success) {
                            this.removeFromStore(userId);
                        }
                        return [2 /*return*/, success];
                }
            });
        });
    };
    UsersStore.prototype.get = function (id) {
        return __awaiter(this, void 0, void 0, function () {
            var _a;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        _a = this.getItem(id);
                        if (_a) return [3 /*break*/, 2];
                        return [4 /*yield*/, this.usersService.get(id)];
                    case 1:
                        _a = (_b.sent());
                        _b.label = 2;
                    case 2: return [2 /*return*/, _a];
                }
            });
        });
    };
    UsersStore.prototype.getMany = function (ids, commonOptions) {
        return __awaiter(this, void 0, void 0, function () {
            var idsSet, uniqIds, foundItems, missingIds, missingUsers, missingIdsChunks, concurrentChunks, concurrentChunks_1, concurrentChunks_1_1, concurrentChunk, promises, rejectReason, results, results_1, results_1_1, result, users, e_8_1;
            var e_8, _a, e_9, _b;
            var _this = this;
            return __generator(this, function (_c) {
                switch (_c.label) {
                    case 0:
                        idsSet = new Set(ids);
                        uniqIds = Array.from(idsSet);
                        foundItems = this.getItemsByIds(uniqIds);
                        if (foundItems.length === uniqIds.length) {
                            return [2 /*return*/, foundItems];
                        }
                        foundItems.forEach(function (user) { return idsSet.delete(user.id); });
                        missingIds = Array.from(idsSet);
                        missingUsers = [];
                        missingIdsChunks = (0, chunk_1.default)(missingIds, exports.DEFAULT_CHUNK_SIZE);
                        concurrentChunks = (0, chunk_1.default)(missingIdsChunks, exports.MAX_CONCURRENT_CHUNKED_REQUESTS);
                        _c.label = 1;
                    case 1:
                        _c.trys.push([1, 6, 7, 8]);
                        concurrentChunks_1 = __values(concurrentChunks), concurrentChunks_1_1 = concurrentChunks_1.next();
                        _c.label = 2;
                    case 2:
                        if (!!concurrentChunks_1_1.done) return [3 /*break*/, 5];
                        concurrentChunk = concurrentChunks_1_1.value;
                        promises = concurrentChunk.map(function (idsChunk) { return __awaiter(_this, void 0, void 0, function () {
                            var chunkResult;
                            return __generator(this, function (_a) {
                                switch (_a.label) {
                                    case 0: return [4 /*yield*/, this.usersService.getMany({ usersIds: idsChunk }, commonOptions)];
                                    case 1:
                                        chunkResult = _a.sent();
                                        return [2 /*return*/, chunkResult.users];
                                }
                            });
                        }); });
                        // Rate limit to one set of requests per MIN_INTERVAL_BETWEEN_CHUNKED_REQUESTS
                        if (concurrentChunk !== (0, last_1.default)(concurrentChunks)) {
                            promises.push(new Promise(function (resolve) { return setTimeout(function () { return resolve([]); }, MIN_INTERVAL_BETWEEN_CHUNKED_REQUESTS); }));
                        }
                        rejectReason = null;
                        return [4 /*yield*/, Promise.allSettled(promises)];
                    case 3:
                        results = _c.sent();
                        try {
                            for (results_1 = (e_9 = void 0, __values(results)), results_1_1 = results_1.next(); !results_1_1.done; results_1_1 = results_1.next()) {
                                result = results_1_1.value;
                                if (result.status === 'fulfilled') {
                                    users = result.value;
                                    missingUsers.push.apply(missingUsers, __spreadArray([], __read(users), false));
                                    this.addItems(users);
                                }
                                else {
                                    if (!rejectReason) {
                                        rejectReason = result.reason;
                                    }
                                }
                            }
                        }
                        catch (e_9_1) { e_9 = { error: e_9_1 }; }
                        finally {
                            try {
                                if (results_1_1 && !results_1_1.done && (_b = results_1.return)) _b.call(results_1);
                            }
                            finally { if (e_9) throw e_9.error; }
                        }
                        if (rejectReason) {
                            throw rejectReason;
                        }
                        _c.label = 4;
                    case 4:
                        concurrentChunks_1_1 = concurrentChunks_1.next();
                        return [3 /*break*/, 2];
                    case 5: return [3 /*break*/, 8];
                    case 6:
                        e_8_1 = _c.sent();
                        e_8 = { error: e_8_1 };
                        return [3 /*break*/, 8];
                    case 7:
                        try {
                            if (concurrentChunks_1_1 && !concurrentChunks_1_1.done && (_a = concurrentChunks_1.return)) _a.call(concurrentChunks_1);
                        }
                        finally { if (e_8) throw e_8.error; }
                        return [7 /*endfinally*/];
                    case 8: return [2 /*return*/, foundItems.concat(missingUsers)];
                }
            });
        });
    };
    UsersStore.prototype.unlock = function (userId) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.usersService.unlock(userId)];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    UsersStore.prototype.assignedTasksCount = function (userId) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.usersService.assignedTasksCount(userId)];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    UsersStore.prototype.totalEmployeesCount = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.usersService.totalEmployeesCount()];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    UsersStore.prototype.totalDriversCount = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.usersService.totalDriversCount()];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    UsersStore.prototype.getProfileImage = function (userId) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.usersService.getProfileImage(userId)];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    UsersStore.prototype.validatePhone = function (phone) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.usersService.validatePhone(phone)];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    UsersStore.prototype.closedTasks = function (userId, page) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.usersService.closedTasks(userId, page)];
                    case 1: return [2 /*return*/, _a.sent()]; // in future - add this tasks to store :)
                }
            });
        });
    };
    UsersStore.prototype.messageDriver = function (userId, message) {
        return this.usersService.messageDriver(userId, message);
    };
    UsersStore.prototype.subscribeToGroupUpdates = function (fn) {
        this.groupUpdateEvents.push(fn);
    };
    UsersStore.prototype.getOfflineDrivers = function () {
        return this.groupedValues.get(User_consts_1.GROUP_VALUES.OfflineDrivers) || new Set();
    };
    UsersStore.prototype.getOnlineDrivers = function () {
        return this.groupedValues.get(User_consts_1.GROUP_VALUES.OnlineDrivers) || new Set();
    };
    UsersStore.prototype.getOnShiftDrivers = function () {
        return Array.from(this.groupedValues.get(User_consts_1.GROUP_VALUES.OnShiftDrivers) || []);
    };
    UsersStore.prototype.getCustomers = function () {
        return Array.from(this.groupedValues.get(User_consts_1.GROUP_VALUES.Customers) || []);
    };
    UsersStore.prototype.getAdmins = function () {
        return Array.from(this.groupedValues.get(User_consts_1.GROUP_VALUES.Admins) || []);
    };
    UsersStore.prototype.getDispatchers = function () {
        return Array.from(this.groupedValues.get(User_consts_1.GROUP_VALUES.Dispatchers) || []);
    };
    UsersStore.prototype.emitGroupEvents = function () {
        var _this = this;
        this.groupUpdateEvents.forEach(function (fn) { return fn(_this.groupedValues); });
    };
    UsersStore.prototype.getAllLocalDrivers = function () {
        return this.drivers;
    };
    UsersStore.prototype.getOnlineDriversCountByTeam = function (teamId) {
        return this.onlineDriversCounterByTeam.get(teamId) || 0;
    };
    UsersStore.prototype.getAllLocalAdminsAndDispatchers = function () {
        return __spreadArray([], __read(new Set(this.getAdmins().concat(this.getDispatchers()))), false);
    };
    return UsersStore;
}(BaseStore_1.default));
exports.default = UsersStore;
//# sourceMappingURL=UsersStore.js.map