"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 __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var lodash_1 = require("lodash");
var BringgException_1 = require("../../Core/BringgException");
var ExceptionReason_1 = require("../../Core/ExceptionReason");
var merge_mapper_1 = require("../../Data/merge-mapper");
var storable_realtime_subscriptions_1 = __importDefault(require("../../Data/storable-realtime-subscriptions"));
var data_entity_1 = require("../../data-entity");
var data_store_1 = __importDefault(require("../../data-store"));
var storable_data_service_1 = __importDefault(require("../../storable-data-service"));
var keyset_pagination_consts_1 = require("../../utils/consts/keyset-pagination.consts");
var User_consts_1 = require("../User.consts");
var users_service_1 = __importDefault(require("./users-service"));
var UsersApi = /** @class */ (function () {
    function UsersApi(session) {
        var _this = this;
        var groupFilters = [
            {
                groupType: User_consts_1.UserGroupTypes.Main,
                keyFunc: function (user) { return (0, User_consts_1.userToGroupsMapper)(user); }
            },
            {
                groupType: 'teamAndDriver',
                keyFunc: function (user) { return (user.driver && user.team_ids) || []; }
            }
        ];
        this.userStore = new data_store_1.default(groupFilters, { shallow: true });
        this.usersService = new users_service_1.default(session);
        this.storableDataService = new storable_data_service_1.default(this.userStore, function (user) {
            return merge_mapper_1.mergeMapper.mergeIntoExisting(_this.userStore, user);
        });
        this.storableRealtimeSubscriptions = new storable_realtime_subscriptions_1.default(session, this.userStore, this.storableDataService);
        this.storableRealtimeSubscriptions.updateStoreOnEvents([
            {
                name: User_consts_1.RealtimeEvents.Update,
                isDelete: false,
                extraDataFunc: function (user) {
                    return { skipStoreUpdate: !_this.userStore.get(user.id) };
                }
            },
            { name: User_consts_1.RealtimeEvents.Create, isDelete: false },
            { name: User_consts_1.RealtimeEvents.Delete, isDelete: true }
        ]);
    }
    UsersApi.prototype.delete = function (userId) {
        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.storableDataService.delete('delete', function () { return __awaiter(_this, void 0, void 0, function () {
                            return __generator(this, function (_a) {
                                switch (_a.label) {
                                    case 0: return [4 /*yield*/, this.usersService.delete(userId)];
                                    case 1:
                                        response = _a.sent();
                                        return [2 /*return*/, response];
                                }
                            });
                        }); }, userId)];
                    case 1:
                        _a.sent();
                        return [2 /*return*/, response];
                }
            });
        });
    };
    UsersApi.prototype.deleteMany = function (userIds) {
        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.storableDataService.deleteMany('deleteMany', function () { return __awaiter(_this, void 0, void 0, function () {
                            return __generator(this, function (_a) {
                                switch (_a.label) {
                                    case 0: return [4 /*yield*/, this.usersService.deleteMany(userIds)];
                                    case 1:
                                        response = _a.sent();
                                        return [2 /*return*/, response];
                                }
                            });
                        }); }, userIds)];
                    case 1:
                        _a.sent();
                        return [2 /*return*/, response];
                }
            });
        });
    };
    UsersApi.prototype.create = function (user) {
        return __awaiter(this, void 0, void 0, function () {
            var _this = this;
            return __generator(this, function (_a) {
                if ((0, lodash_1.isNil)(user.email) && (0, lodash_1.isNil)(user.phone)) {
                    throw new BringgException_1.BringgException(ExceptionReason_1.ExceptionReason.INVALID_ARGUMENTS, 'Phone or Email is required');
                }
                return [2 /*return*/, this.storableDataService.modify('create', function () { return _this.usersService.create(user); })];
            });
        });
    };
    UsersApi.prototype.update = function (userId, userDelta) {
        return __awaiter(this, void 0, void 0, function () {
            var _this = this;
            return __generator(this, function (_a) {
                return [2 /*return*/, this.storableDataService.modify('update', function () { return _this.usersService.update(userId, userDelta); }, function (modifiedUser) {
                        var currentUser = _this.usersService.session.user;
                        if (currentUser.id === modifiedUser.current.id) {
                            _this.usersService.session.user = (0, lodash_1.merge)(currentUser, modifiedUser.current);
                            _this.usersService.session.sendDataEvent(User_consts_1.UserEvents.CURRENT_USER_UPDATED, _this.usersService.session.user);
                        }
                    })];
            });
        });
    };
    UsersApi.prototype.load = function (userId, options) {
        if (options === void 0) { options = data_entity_1.DEFAULT_OPTIONS; }
        return __awaiter(this, void 0, void 0, function () {
            var _this = this;
            return __generator(this, function (_a) {
                return [2 /*return*/, this.storableDataService.load('load', function () { return _this.usersService.get(userId); }, userId, options)];
            });
        });
    };
    UsersApi.prototype.loadMany = function (ids, options) {
        if (options === void 0) { options = { useCache: true }; }
        return __awaiter(this, void 0, void 0, function () {
            var chunkSize;
            var _this = this;
            return __generator(this, function (_a) {
                if (ids.length === 0) {
                    return [2 /*return*/, []];
                }
                chunkSize = options.chunkSize || 500;
                return [2 /*return*/, this.storableDataService.loadMany('loadMany', function (idsToLoad) { return __awaiter(_this, void 0, void 0, function () {
                        var users;
                        return __generator(this, function (_a) {
                            switch (_a.label) {
                                case 0: return [4 /*yield*/, this.usersService.loadMany({ ids: idsToLoad, limit: chunkSize, page: 1 })];
                                case 1:
                                    users = _a.sent();
                                    return [2 /*return*/, users];
                            }
                        });
                    }); }, ids, __assign(__assign({}, options), { chunkSize: chunkSize }))];
            });
        });
    };
    UsersApi.prototype.loadAllByTeam = function (teamId, options) {
        return __awaiter(this, void 0, void 0, function () {
            var _this = this;
            return __generator(this, function (_a) {
                return [2 /*return*/, this.storableDataService.loadAll('loadDriversByTeam', function () { return __awaiter(_this, void 0, void 0, function () {
                        var users;
                        return __generator(this, function (_a) {
                            switch (_a.label) {
                                case 0: return [4 /*yield*/, this.usersService.loadAllByTeams(teamId)];
                                case 1:
                                    users = _a.sent();
                                    return [2 /*return*/, users];
                            }
                        });
                    }); }, __assign(__assign({}, options), { groupType: 'teamAndDriver', groupValue: teamId }))];
            });
        });
    };
    // Pagination methods
    UsersApi.prototype.loadAll = function (_a) {
        var _b = _a === void 0 ? {} : _a, _c = _b.limit, limit = _c === void 0 ? 2500 : _c, page = _b.page, _d = _b.page_action, page_action = _d === void 0 ? keyset_pagination_consts_1.KeysetPaginationPageAction.NEXT : _d, cursor = _b.cursor, options = _b.options;
        return __awaiter(this, void 0, void 0, function () {
            var loadResult, loadFunc, users;
            var _this = this;
            return __generator(this, function (_e) {
                switch (_e.label) {
                    case 0:
                        loadFunc = function () { return __awaiter(_this, void 0, void 0, function () {
                            var response;
                            return __generator(this, function (_a) {
                                switch (_a.label) {
                                    case 0: return [4 /*yield*/, this.usersService.loadAll({ limit: limit, page: page, page_action: page_action, cursor: cursor }, { signal: options === null || options === void 0 ? void 0 : options.signal })];
                                    case 1:
                                        response = _a.sent();
                                        loadResult = response;
                                        return [2 /*return*/, response.users];
                                }
                            });
                        }); };
                        return [4 /*yield*/, this.storableDataService.loadMany('loadAll', loadFunc, [], options)];
                    case 1:
                        users = _e.sent();
                        return [2 /*return*/, __assign(__assign({}, loadResult), { users: users })];
                }
            });
        });
    };
    UsersApi.prototype.getAllDrivers = function (_a) {
        var _b = _a.limit, limit = _b === void 0 ? 25 : _b, _c = _a.page_action, page_action = _c === void 0 ? keyset_pagination_consts_1.KeysetPaginationPageAction.NEXT : _c, cursor = _a.cursor, options = _a.options;
        return __awaiter(this, void 0, void 0, function () {
            var optionsWithDefaults, loadResult, loadFunc, users;
            var _this = this;
            return __generator(this, function (_d) {
                switch (_d.label) {
                    case 0:
                        optionsWithDefaults = (0, lodash_1.defaults)(options, { onlyOnlineDriver: false, onlyCustomers: false });
                        loadFunc = function () { return __awaiter(_this, void 0, void 0, function () {
                            var result;
                            return __generator(this, function (_a) {
                                switch (_a.label) {
                                    case 0: return [4 /*yield*/, this.usersService.getAllDrivers({
                                            limit: limit,
                                            page_action: page_action,
                                            cursor: cursor,
                                            options: optionsWithDefaults
                                        })];
                                    case 1:
                                        result = _a.sent();
                                        loadResult = result;
                                        return [2 /*return*/, result.users];
                                }
                            });
                        }); };
                        return [4 /*yield*/, this.storableDataService.loadMany('getAllDrivers', loadFunc, [])];
                    case 1:
                        users = _d.sent();
                        return [2 /*return*/, __assign(__assign({}, loadResult), { users: users })];
                }
            });
        });
    };
    UsersApi.prototype.getAllAdminsAndDispatchers = function (_a) {
        var _b = _a.limit, limit = _b === void 0 ? 25 : _b, _c = _a.page_action, page_action = _c === void 0 ? keyset_pagination_consts_1.KeysetPaginationPageAction.NEXT : _c, cursor = _a.cursor, options = _a.options;
        return __awaiter(this, void 0, void 0, function () {
            var loadResult, loadFunc, users;
            var _this = this;
            return __generator(this, function (_d) {
                switch (_d.label) {
                    case 0:
                        loadFunc = function () { return __awaiter(_this, void 0, void 0, function () {
                            var result;
                            return __generator(this, function (_a) {
                                switch (_a.label) {
                                    case 0: return [4 /*yield*/, this.usersService.getAllAdminsAndDispatchers({
                                            limit: limit,
                                            page_action: page_action,
                                            cursor: cursor
                                        })];
                                    case 1:
                                        result = _a.sent();
                                        loadResult = result;
                                        return [2 /*return*/, result.users];
                                }
                            });
                        }); };
                        return [4 /*yield*/, this.storableDataService.loadMany('getAllAdminsAndDispatchers', loadFunc, [])];
                    case 1:
                        users = _d.sent();
                        return [2 /*return*/, __assign(__assign({}, loadResult), { users: users })];
                }
            });
        });
    };
    // Business logic methods
    UsersApi.prototype.messageDriver = function (userId, message) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, this.usersService.messageDriver(userId, message)];
            });
        });
    };
    UsersApi.prototype.unlock = function (userId) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, this.usersService.unlock(userId)];
            });
        });
    };
    UsersApi.prototype.validatePhone = function (phone) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, this.usersService.validatePhone(phone)];
            });
        });
    };
    UsersApi.prototype.getDriverCost = function (userId) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, this.usersService.getDriverCost(userId)];
            });
        });
    };
    UsersApi.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.storableDataService.updateInStores(user);
                        return [2 /*return*/, user];
                }
            });
        });
    };
    UsersApi.prototype.closedTasks = function (userId, page) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, this.usersService.closedTasks(userId, page)];
            });
        });
    };
    UsersApi.prototype.assignedTasksCount = function (userId) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, this.usersService.assignedTasksCount(userId)];
            });
        });
    };
    UsersApi.prototype.byUserType = function (userTypeId) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, this.usersService.byUserType(userTypeId)];
            });
        });
    };
    // Store query methods - direct access to local store without API calls
    UsersApi.prototype.getGroup = function (group) {
        return this.userStore.getGroup(User_consts_1.UserGroupTypes.Main, group);
    };
    UsersApi.prototype.getTeamGroup = function (teamId) {
        return this.userStore.getGroup('teamAndDriver', teamId);
    };
    UsersApi.prototype.get = function (id) {
        return this.userStore.get(id);
    };
    UsersApi.prototype.getMany = function (ids) {
        return this.userStore.getMany(ids);
    };
    UsersApi.prototype.getAll = function () {
        return this.userStore.getAll();
    };
    UsersApi.prototype.getOfflineDrivers = function () {
        var group = this.userStore.getGroup(User_consts_1.UserGroupTypes.Main, User_consts_1.GROUP_VALUES.OfflineDrivers);
        return group ? Array.from(group) : [];
    };
    UsersApi.prototype.getOnlineDrivers = function () {
        var group = this.userStore.getGroup(User_consts_1.UserGroupTypes.Main, User_consts_1.GROUP_VALUES.OnlineDrivers);
        return group ? Array.from(group) : [];
    };
    UsersApi.prototype.getAllLocalDrivers = function () {
        var group = this.userStore.getGroup(User_consts_1.UserGroupTypes.Main, User_consts_1.GROUP_VALUES.Drivers);
        return group ? Array.from(group) : [];
    };
    UsersApi.prototype.getOnShiftDrivers = function () {
        var group = this.userStore.getGroup(User_consts_1.UserGroupTypes.Main, User_consts_1.GROUP_VALUES.OnShiftDrivers);
        return group ? Array.from(group) : [];
    };
    // Additional callback methods
    UsersApi.prototype.onCreate = function (callback) {
        return this.storableRealtimeSubscriptions.onEvent(User_consts_1.RealtimeEvents.Create, callback);
    };
    UsersApi.prototype.onUpdate = function (callback, options) {
        return this.storableRealtimeSubscriptions.onEvent(User_consts_1.RealtimeEvents.Update, callback, options);
    };
    UsersApi.prototype.onDelete = function (callback) {
        return this.storableRealtimeSubscriptions.onEvent(User_consts_1.RealtimeEvents.Delete, callback);
    };
    return UsersApi;
}());
exports.default = UsersApi;
//# sourceMappingURL=users-api.js.map