"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 __rest = (this && this.__rest) || function (s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                t[p[i]] = s[p[i]];
        }
    return t;
};
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 });
var types_1 = require("@bringg/types");
var light_data_store_1 = __importDefault(require("../../Data/light-data-store"));
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 Tasks_consts_1 = require("../Tasks.consts");
var task_merger_1 = require("./task-merger");
var task_realtime_subscriptions_1 = __importDefault(require("./task-realtime-subscriptions"));
var tasks_service_1 = __importDefault(require("./tasks-service"));
// hard coded fields to take advantage of the light data store cache
var READY_TO_EXECUTE_FIELDS = ['ready_to_execute'];
var TasksApi = /** @class */ (function () {
    function TasksApi(session) {
        var _this = this;
        var groupFilters = [
            {
                groupType: Tasks_consts_1.TaskGroupTypes.Main,
                keyFunc: function (task) {
                    if (task.invalidated) {
                        return Tasks_consts_1.GROUP_VALUES.Invalid;
                    }
                    else if (task.group_leader_id) {
                        return Tasks_consts_1.GROUP_VALUES.Followers;
                    }
                    else if ([types_1.TaskStatus.Done, types_1.TaskStatus.Cancelled].indexOf(task.status) !== -1) {
                        return Tasks_consts_1.GROUP_VALUES.Closed;
                    }
                    else if (task.status === types_1.TaskStatus.Unacknowledged) {
                        return Tasks_consts_1.GROUP_VALUES.Unacknowledged;
                    }
                    else if (task.ready_to_execute) {
                        return Tasks_consts_1.GROUP_VALUES.Open;
                    }
                    else {
                        return Tasks_consts_1.GROUP_VALUES.Planning;
                    }
                }
            },
            {
                groupType: Tasks_consts_1.TaskGroupTypes.Followers,
                keyFunc: function (task) { return task.group_leader_id; }
            }
        ];
        this.tasksStore = new data_store_1.default(groupFilters, { shallow: true });
        this.tasksService = new tasks_service_1.default(session);
        var lightDataStore = new light_data_store_1.default();
        this.storableDataService = new storable_data_service_1.default(this.tasksStore, function (task, params) {
            return task_merger_1.taskMerger.mergeTaskIntoExisting({
                tasksStore: _this.tasksStore,
                task: task,
                params: params
            });
        }, [lightDataStore]);
        this.taskRealtimeSubscriptions = new task_realtime_subscriptions_1.default(session, this.tasksStore, this.storableDataService);
    }
    TasksApi.prototype.updateStoreOnEvents = function () {
        this.taskRealtimeSubscriptions.updateStoreOnEvents();
    };
    TasksApi.prototype.onUpdate = function (callback) {
        return this.taskRealtimeSubscriptions.onUpdate(callback);
    };
    TasksApi.prototype.onCreate = function (callback) {
        return this.taskRealtimeSubscriptions.onCreate(callback);
    };
    TasksApi.prototype.onDelete = function (callback) {
        return this.taskRealtimeSubscriptions.onDelete(callback);
    };
    TasksApi.prototype.onWayPointUpdate = function (callback) {
        return this.taskRealtimeSubscriptions.onWayPointUpdate(callback);
    };
    TasksApi.prototype.onWayPointDelete = function (callback) {
        return this.taskRealtimeSubscriptions.onWayPointDelete(callback);
    };
    TasksApi.prototype.get = function (id, fields) {
        return this.getMany([id], this.getFieldsToLoad(fields))[0];
    };
    TasksApi.prototype.getMany = function (ids, fields) {
        return this.storableDataService.getFromStores(ids, this.getFieldsToLoad(fields));
    };
    TasksApi.prototype.getGroup = function (groupType, groupValue) {
        return this.tasksStore.getGroup(groupType, groupValue);
    };
    TasksApi.prototype.isInGroup = function (taskId, groupType, groupValue) {
        return this.tasksStore.isInGroup(taskId, groupType, groupValue);
    };
    TasksApi.prototype.getAllById = function () {
        return this.tasksStore.getAllById();
    };
    TasksApi.prototype.load = function (id, options) {
        var _this = this;
        if (options === void 0) { options = data_entity_1.DEFAULT_OPTIONS; }
        return this.storableDataService.load('load', function () { return _this.tasksService.load(id); }, id, options);
    };
    TasksApi.prototype.loadMany = function (ids, fields, options) {
        if (options === void 0) { options = data_entity_1.DEFAULT_OPTIONS; }
        return __awaiter(this, void 0, void 0, function () {
            var allFields;
            var _this = this;
            return __generator(this, function (_a) {
                allFields = this.getFieldsToLoad(fields);
                return [2 /*return*/, this.storableDataService.loadMany('batchLoad', function (idsToLoad) { return _this.tasksService.batchLoad(idsToLoad, allFields, { signal: options.signal }); }, ids, __assign(__assign({}, options), { fields: allFields }))];
            });
        });
    };
    TasksApi.prototype.loadPlanning = function (columns, options) {
        if (options === void 0) { options = data_entity_1.DEFAULT_OPTIONS; }
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, this.loadKeySet('loadPlanningTasks', columns, __assign(__assign({}, options), { groupType: Tasks_consts_1.TaskGroupTypes.Main, groupValue: Tasks_consts_1.GROUP_VALUES.Planning }))];
            });
        });
    };
    TasksApi.prototype.loadOpen = function (columns, options) {
        if (options === void 0) { options = data_entity_1.DEFAULT_OPTIONS; }
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, this.loadKeySet('loadOpenTasks', columns, __assign(__assign({}, options), { groupType: Tasks_consts_1.TaskGroupTypes.Main, groupValue: Tasks_consts_1.GROUP_VALUES.Open }))];
            });
        });
    };
    TasksApi.prototype.loadKeySet = function (action, columns, options) {
        if (options === void 0) { options = data_entity_1.DEFAULT_OPTIONS; }
        return __awaiter(this, void 0, void 0, function () {
            var loadResult, request;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        request = {
                            limit: options.chunkSize,
                            page_action: keyset_pagination_consts_1.KeysetPaginationPageAction.NEXT_ONLY,
                            pgver: keyset_pagination_consts_1.KEYSET_PAGINATION_VER,
                            columns: columns,
                            cursor: options.cursor,
                            team_ids: options.teamIds
                        };
                        return [4 /*yield*/, this.storableDataService.loadMany(action, 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.tasksService[action](request)];
                                        case 1:
                                            result = _a.sent();
                                            loadResult = result;
                                            return [2 /*return*/, result.items];
                                    }
                                });
                            }); }, [], __assign(__assign({}, options), { fields: this.getFieldsToLoad(columns) }))];
                    case 1:
                        _a.sent();
                        if (!loadResult.next_page_cursor) {
                            this.tasksStore.setGroupInitialized(options.groupType, options.groupValue);
                        }
                        return [2 /*return*/, __assign(__assign({}, loadResult), { items: loadResult.items.map(function (item) { return _this.tasksStore.get(item.id); }) })];
                }
            });
        });
    };
    TasksApi.prototype.massAssign = function (userId, taskIds, options, targetRun) {
        return this.tasksService.massAssign(userId, taskIds, options, targetRun);
    };
    TasksApi.prototype.massUnassign = function (taskIds, options) {
        return this.tasksService.massUnassign(taskIds, options);
    };
    TasksApi.prototype.massCancel = function (taskIds, reasonId, text, automaticallyCancelled) {
        return this.tasksService.massCancel(taskIds, reasonId, text, automaticallyCancelled);
    };
    TasksApi.prototype.loadInvalid = function (_a) {
        var _this = this;
        if (_a === void 0) { _a = {}; }
        var columns = _a.columns, options = __rest(_a, ["columns"]);
        return this.storableDataService.loadAll('loadInvalid', function () { return _this.tasksService.loadInvalid(columns); }, __assign(__assign(__assign({}, data_entity_1.DEFAULT_OPTIONS), options), { fields: this.getFieldsToLoad(columns), groupType: Tasks_consts_1.TaskGroupTypes.Main, groupValue: Tasks_consts_1.GROUP_VALUES.Invalid }));
    };
    TasksApi.prototype.broadcastToDrivers = function (id, userIds, message) {
        return this.tasksService.broadcastToDrivers(id, userIds, message);
    };
    TasksApi.prototype.acknowledgeTask = function (id) {
        var _this = this;
        return this.storableDataService.modify('acknowledgeTask', function () { return _this.tasksService.acknowledgeTask(id); }, function (modifiedItem) { return _this.taskRealtimeSubscriptions.callRealTimeEvent(modifiedItem); });
    };
    TasksApi.prototype.releaseToDrivers = function (ids) {
        return __awaiter(this, void 0, void 0, function () {
            var result;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.storableDataService.modifyMany('releaseToDrivers', function () { return __awaiter(_this, void 0, void 0, function () {
                            return __generator(this, function (_a) {
                                switch (_a.label) {
                                    case 0: return [4 /*yield*/, this.tasksService.releaseToDrivers(ids)];
                                    case 1:
                                        result = _a.sent();
                                        return [2 /*return*/, ids.map(function (id) { return ({ id: id, ready_to_execute: true }); })];
                                }
                            });
                        }); }, READY_TO_EXECUTE_FIELDS, function (modifiedItem) { return _this.taskRealtimeSubscriptions.callUpdateTaskRealTimeEvents(modifiedItem); })];
                    case 1:
                        _a.sent();
                        return [2 /*return*/, result];
                }
            });
        });
    };
    TasksApi.prototype.moveToPlanning = function (ids) {
        return __awaiter(this, void 0, void 0, function () {
            var result;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.storableDataService.modifyMany('releaseToDrivers', function () { return __awaiter(_this, void 0, void 0, function () {
                            return __generator(this, function (_a) {
                                switch (_a.label) {
                                    case 0: return [4 /*yield*/, this.tasksService.moveToPlanning(ids)];
                                    case 1:
                                        result = _a.sent();
                                        return [2 /*return*/, ids.map(function (id) { return ({ id: id, ready_to_execute: false }); })];
                                }
                            });
                        }); }, READY_TO_EXECUTE_FIELDS, function (modifiedItem) { return _this.taskRealtimeSubscriptions.callUpdateTaskRealTimeEvents(modifiedItem); })];
                    case 1:
                        _a.sent();
                        return [2 /*return*/, result];
                }
            });
        });
    };
    TasksApi.prototype.update = function (task) {
        var _this = this;
        return this.storableDataService.modify('update', function () { return _this.tasksService.update(task); }, function (modifiedItem) { return _this.taskRealtimeSubscriptions.callRealTimeEvent(modifiedItem); });
    };
    TasksApi.prototype.updatePreparationStatus = function (taskId, preparationStatus) {
        var _this = this;
        return this.storableDataService.modify('updatePreparationStatus', function () { return _this.tasksService.updatePreparationStatus(taskId, preparationStatus); }, function (modifiedItem) { return _this.taskRealtimeSubscriptions.callRealTimeEvent(modifiedItem); });
    };
    TasksApi.prototype.rescheduleVirtualTasks = function (taskIds, noLaterThan, noEarlierThan) {
        return this.tasksService.rescheduleVirtualTasks(taskIds, noLaterThan, noEarlierThan);
    };
    TasksApi.prototype.duplicate = function (taskId) {
        var _this = this;
        return this.storableDataService.modify('duplicate', function () { return _this.tasksService.duplicate(taskId); }, function (modifiedItem) { return _this.taskRealtimeSubscriptions.callRealTimeEvent(modifiedItem); });
    };
    TasksApi.prototype.cancel = function (id) {
        var _this = this;
        return this.storableDataService.modify('cancel', function () {
            return _this.tasksService.cancel(id);
        }, function (modifiedItem) { return _this.taskRealtimeSubscriptions.callRealTimeEvent(modifiedItem); });
    };
    TasksApi.prototype.getChildTasks = function (taskId) {
        return this.tasksService.getChildTasks(taskId);
    };
    TasksApi.prototype.lock = function (taskIds) {
        return this.tasksService.lock(taskIds);
    };
    TasksApi.prototype.unlock = function (taskIds) {
        return this.tasksService.unlock(taskIds);
    };
    TasksApi.prototype.finish = function (id) {
        var _this = this;
        return this.storableDataService.modify('finish', function () { return _this.tasksService.finish(id); }, function (modifiedItem) { return _this.taskRealtimeSubscriptions.callRealTimeEvent(modifiedItem); });
    };
    TasksApi.prototype.rescheduleCancelled = function (taskId) {
        return this.tasksService.rescheduleCancelled(taskId);
    };
    TasksApi.prototype.getRescheduleQuote = function (taskId) {
        return this.tasksService.getRescheduleQuote(taskId);
    };
    TasksApi.prototype.addTaskNote = function (taskId, wayPointId, note, type, image, hiddenFromDrivers) {
        return this.tasksService.addTaskNote(taskId, wayPointId, note, type, image, hiddenFromDrivers);
    };
    TasksApi.prototype.getLocations = function (taskId) {
        return this.tasksService.getLocations(taskId);
    };
    TasksApi.prototype.deleteWayPoint = function (taskId, wayPointId) {
        return this.tasksService.deleteWayPoint(taskId, wayPointId);
    };
    TasksApi.prototype.importTasksCsv = function (file) {
        return this.tasksService.importTasksCsv(file);
    };
    TasksApi.prototype.activityLog = function (taskId) {
        return this.tasksService.activityLog(taskId);
    };
    TasksApi.prototype.massDeleteGroups = function (groupLeaderTaskIds) {
        return this.tasksService.massDeleteGroups(groupLeaderTaskIds);
    };
    TasksApi.prototype.hasDefectiveGeocode = function () {
        return this.tasksService.hasDefectiveGeocode();
    };
    TasksApi.prototype.getFieldsToLoad = function (fields) {
        if (!fields) {
            return fields;
        }
        if (typeof fields === 'string') {
            fields = fields.split(',');
        }
        var allFields = __spreadArray([], __read(fields), false);
        Tasks_consts_1.taskDefaultFields.forEach(function (field) {
            if (typeof field === 'object') {
                if (field['way_points']) {
                    var wayPointsIndex = allFields.findIndex(function (field) { return typeof field === 'object' && field['way_points']; });
                    var wayPointsFields_1 = wayPointsIndex > -1 ? allFields.splice(wayPointsIndex, 1)[0]['way_points'] : [];
                    field['way_points'].forEach(function (wayPointField) {
                        if (!wayPointsFields_1.includes(wayPointField)) {
                            wayPointsFields_1.push(wayPointField);
                        }
                    });
                    allFields.push({ way_points: wayPointsFields_1 });
                }
            }
            else if (!fields.includes(field)) {
                allFields.push(field);
            }
        });
        // To take advantage of the LightData store cache
        if (allFields.length === fields.length) {
            return fields;
        }
        return allFields;
    };
    return TasksApi;
}());
exports.default = TasksApi;
//# sourceMappingURL=tasks-api.js.map