"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 __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 __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 lodash_1 = require("lodash");
var rxjs_1 = require("rxjs");
var operators_1 = require("rxjs/operators");
var Entity_1 = require("../../Core/Entity");
var StoreEntity_1 = __importDefault(require("../../Core/StoreEntity"));
var keyset_pagination_consts_1 = require("../../utils/consts/keyset-pagination.consts");
var TaskHelpers_1 = require("../TaskHelpers");
var Tasks_consts_1 = require("../Tasks.consts");
var THROTTLE_TIME = 500;
var TaskEntity = /** @class */ (function (_super) {
    __extends(TaskEntity, _super);
    function TaskEntity(session, throttleTimeValue) {
        var _this = _super.call(this, {
            session: session,
            entityName: 'tasks',
            routes: [Entity_1.BaseRoutes.Create, Entity_1.BaseRoutes.Get, Entity_1.BaseRoutes.Update]
        }) || this;
        _this.groupUpdateEvents = [];
        _this.groupedValues = new Map();
        /* RealTime Handle Events */
        _this.registerOnWayPointUpdate = function (fn) {
            return _this.registerOnEvent(Tasks_consts_1.TaskRealTimeEvents.WAYPOINT_UPDATED, fn);
        };
        _this.registerOnWayPointAdded = function (fn) {
            return _this.registerOnEvent(Tasks_consts_1.TaskRealTimeEvents.WAYPOINT_ADDED, fn);
        };
        _this.registerOnWayPointDeleted = function (fn) {
            return _this.registerOnEvent(Tasks_consts_1.TaskRealTimeEvents.WAYPOINT_DELETED, fn);
        };
        _this.onUpdateTask = function (task) {
            _this.updateTask(task);
        };
        _this.onNewTaskAdded = function (task) {
            _this.addOrUpdateTask(task);
            _this.onCreate(_this.store.getItem(task.id));
        };
        _this.onTaskDelete = function (task) {
            var existingTask = _this.store.getItem(task.id);
            if (existingTask) {
                _this.store.removeFromStore(existingTask.id);
                _this.onDelete(existingTask);
            }
        };
        _this.onWayPointAdded = function (wayPoint) {
            var task = _this.store.getItem(wayPoint.task_id);
            if (task) {
                task.way_points.push(wayPoint);
                task.way_points = (0, lodash_1.sortBy)(task.way_points, 'position');
                _this.updateTask(task);
            }
        };
        _this.onWayPointDeleted = function (wayPoint) {
            var task = _this.store.getItem(wayPoint.task_id);
            if (task) {
                (0, lodash_1.remove)(task.way_points, function (taskWayPoint) { return taskWayPoint.id === wayPoint.id; });
                _this.updateTask(task);
            }
        };
        _this.onWayPointUpdate = function (wayPoint) {
            var task = _this.store.getItem(wayPoint.task_id);
            if (task) {
                var oldWayPoint = (0, lodash_1.find)(task.way_points, function (taskWayPoint) { return taskWayPoint.id == wayPoint.id; });
                (0, lodash_1.merge)(oldWayPoint, wayPoint);
                _this.updateTask(task);
            }
        };
        _this.onNewScanAdded = function (scan) {
            var task = _this.store.getItem(scan.task_id);
            if (task) {
                task.scans.push(scan);
                _this.updateTask(task);
            }
        };
        _this.onNewNoteAdded = function (note) {
            var task = _this.store.getItem(note.task_id);
            if (task) {
                var taskNote = (0, lodash_1.find)(task.task_notes, { id: note.id });
                if (!taskNote) {
                    if (!task.task_notes) {
                        task.task_notes = [];
                    }
                    task.task_notes.push(note);
                    _this.updateTask(task);
                }
            }
        };
        /*------*/
        /* Inner Helper Functions */
        _this.handleTasksRequest = function (route, options) { return __awaiter(_this, void 0, void 0, function () {
            var request, tasks, filteredTasks;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        request = this.service.routeGenerator
                            .get(route)
                            .withExtractor(Tasks_consts_1.defaultExtractor)
                            .setException("failed to fetch ".concat(route, " tasks"));
                        if (options) {
                            request.withQueryString(options);
                        }
                        return [4 /*yield*/, request.invoke()];
                    case 1:
                        tasks = _a.sent();
                        filteredTasks = [];
                        tasks.forEach(function (task) {
                            var updatedTask = _this.addOrUpdateTask(task);
                            if (updatedTask) {
                                filteredTasks.push(updatedTask);
                            }
                        });
                        return [2 /*return*/, filteredTasks];
                }
            });
        }); };
        _this.handleTasksKeySetPaginationRequest = function (route, options) { return __awaiter(_this, void 0, void 0, function () {
            var requestParams, _a, tasks, next_page_cursor, previous_page_cursor, filteredTasks;
            var _this = this;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        requestParams = { pgver: keyset_pagination_consts_1.KEYSET_PAGINATION_VER };
                        if (options) {
                            requestParams = __assign(__assign({}, options), requestParams);
                        }
                        return [4 /*yield*/, this.service.routeGenerator
                                .get(route)
                                .withQueryString(requestParams)
                                .withExtractor(function (res) { return ({
                                next_page_cursor: res.next_page_cursor,
                                previous_page_cursor: res.previous_page_cursor,
                                tasks: res.items
                            }); })
                                .setException("failed to fetch ".concat(route, " tasks"))
                                .invoke()];
                    case 1:
                        _a = _b.sent(), tasks = _a.tasks, next_page_cursor = _a.next_page_cursor, previous_page_cursor = _a.previous_page_cursor;
                        filteredTasks = [];
                        tasks.forEach(function (task) {
                            var updatedTask = _this.addOrUpdateTask(task);
                            if (updatedTask) {
                                filteredTasks.push(updatedTask);
                            }
                        });
                        return [2 /*return*/, {
                                next_page_cursor: next_page_cursor,
                                previous_page_cursor: previous_page_cursor,
                                tasks: filteredTasks
                            }];
                }
            });
        }); };
        _this.shouldAddTask = function (task) { return !TaskHelpers_1.TaskHelpers.isGroupFollower(task); };
        _this.sendRealTimeTaskUpdate = function (task) {
            _this.onUpdate(_this.store.getItem(task.id));
        };
        _this.updateTask = function (task) {
            var updatedTask = _this.addOrUpdateTask(task);
            if (updatedTask) {
                _this.sendRealTimeTaskUpdate(updatedTask);
            }
        };
        _this.addOrUpdateTask = function (task) {
            if (!_this.shouldAddTask(task)) {
                return;
            }
            _this.storeItem(task);
            return _this.store.getItem(task.id);
        };
        _this.importTasksCsv = function (file) {
            var formData = new FormData();
            formData.append('file', file);
            return _this.service.routeGenerator
                .post(Tasks_consts_1.Routes.IMPORT_TASKS_CSV)
                .withHeaders({ 'Content-Type': 'multipart/form-data' })
                .withPayload(formData)
                .invoke();
        };
        _this.broadcastToDrivers = function (taskId, userIds, message) {
            return _this.service.routeGenerator
                .post(Tasks_consts_1.Routes.BROADCAST_TO_DRIVERS)
                .withPayload({ task_id: taskId, user_ids: userIds, message: message })
                .setException("failed to broadcast to drivers task : ".concat(taskId))
                .invoke();
        };
        _this.addTaskNote = function (taskId, wayPointId, note, type, image, hiddenFromDrivers) {
            return _this.service.routeGenerator
                .post(Tasks_consts_1.Routes.CREATE_TASK_NOTE)
                .withRouteParams({ id: taskId, way_point_id: wayPointId })
                .withQueryString({ note: note })
                .withPayload({ type: type, image: image, hidden_from_drivers: hiddenFromDrivers })
                .setException("failed to add note to task : ".concat(taskId))
                .withExtractor(Tasks_consts_1.taskExtractor)
                .invoke();
        };
        _this.deleteWayPoint = function (taskId, wayPointId) {
            return _this.service.routeGenerator
                .delete(Tasks_consts_1.Routes.DELETE_WAYPOINT)
                .withRouteParams({ id: taskId, way_point_id: wayPointId })
                .setException("failed to delete waypoint : task ".concat(taskId, ", waypoint ").concat(wayPointId))
                .invoke();
        };
        _this.getWayPointAnswers = function (taskId, wayPointId) {
            return _this.service.routeGenerator
                .get(Tasks_consts_1.Routes.GET_WAYPOINT_ANSWERS)
                .withRouteParams({ id: taskId, way_point_id: wayPointId })
                .setException("failed to get answers for task ".concat(taskId, " and waypoint ").concat(wayPointId))
                .withExtractor(Tasks_consts_1.answersExtractor)
                .invoke();
        };
        // so we can past configuration in future
        throttleTimeValue = throttleTimeValue || THROTTLE_TIME;
        //group by and save ids | can add config to throttle through users( maybe increase if admin )
        _this.store.state$
            .pipe((0, operators_1.throttleTime)(throttleTimeValue, rxjs_1.asyncScheduler, { trailing: true, leading: false }))
            .subscribe(function (map) {
            (0, rxjs_1.from)(map.values())
                .pipe((0, operators_1.groupBy)(Tasks_consts_1.taskToGroupMapper, function (task) { return task.id; }), (0, operators_1.mergeMap)(function (group) {
                return (0, rxjs_1.zip)((0, rxjs_1.of)(group.key), group.pipe((0, operators_1.toArray)()));
            }))
                .subscribe(function (_a) {
                var _b = __read(_a, 2), groupId = _b[0], groupValues = _b[1];
                _this.groupedValues.set(groupId, groupValues);
                _this.emitGroupEvents();
            });
        });
        return _this;
    }
    TaskEntity.prototype.getGroupsCount = function () {
        return this.groupedValues.size;
    };
    TaskEntity.prototype.subscribeToGroupUpdates = function (fn) {
        this.groupUpdateEvents.push(fn);
    };
    TaskEntity.prototype.emitGroupEvents = function () {
        var _this = this;
        this.groupUpdateEvents.forEach(function (fn) { return fn(_this.groupedValues); });
    };
    TaskEntity.prototype.getOpenTasksIds = function () {
        return this.groupedValues.get(Tasks_consts_1.GROUP_VALUES.Open) || [];
    };
    TaskEntity.prototype.getPlanningTasksIds = function () {
        return this.groupedValues.get(Tasks_consts_1.GROUP_VALUES.Planning) || [];
    };
    TaskEntity.prototype.getGeneralTasksIds = function () {
        return this.groupedValues.get(Tasks_consts_1.GROUP_VALUES.General) || [];
    };
    TaskEntity.prototype.getInvalidTasksIds = function () {
        return this.groupedValues.get(Tasks_consts_1.GROUP_VALUES.Invalid) || [];
    };
    TaskEntity.prototype.getChildTasks = function (taskId) {
        return this.service.routeGenerator
            .get(Tasks_consts_1.Routes.GET_CHILD_TASKS)
            .withExtractor(Tasks_consts_1.childTasksExtractor)
            .withRouteParams({ id: taskId })
            .setException("failed to get child tasks for task ".concat(taskId))
            .invoke();
    };
    TaskEntity.prototype.getPickupQRCode = function (taskId) {
        return this.service.routeGenerator
            .get(Tasks_consts_1.Routes.GET_PICKUP_QR_CODE)
            .withExtractor(Tasks_consts_1.scanCodeExtractor)
            .withRouteParams({ id: taskId })
            .setException("failed to get QR code for task ".concat(taskId))
            .invoke();
    };
    TaskEntity.prototype.rescheduleVirtualTasks = function (taskIds, noLaterThan, noEarlierThan) {
        return this.service.routeGenerator
            .post(Tasks_consts_1.Routes.RESCHEDULE_VIRTUAL_TASKS)
            .withExtractor(Tasks_consts_1.taskIdsExtractor)
            .withPayload({ task_ids: taskIds, no_later_than: noLaterThan, no_earlier_than: noEarlierThan })
            .setException("failed to get reschedule virtual tasks for tasks : [".concat(taskIds.join(', '), "]"))
            .invoke();
    };
    TaskEntity.prototype.rescheduleCancelled = function (id) {
        return this.service.routeGenerator
            .post(Tasks_consts_1.Routes.RESCHEDULE_CANCELED)
            .withExtractor(Tasks_consts_1.successExtractor)
            .withPayload({ id: id })
            .setException("failed to reschedule cancelled task ".concat(id))
            .invoke();
    };
    TaskEntity.prototype.unlock = function (taskIds) {
        return this.service.routeGenerator
            .post(Tasks_consts_1.Routes.UNLOCK_TASK)
            .withExtractor(Tasks_consts_1.successExtractor)
            .withPayload({ task_ids: taskIds })
            .setException("failed to unlock the tasks [".concat(taskIds.join(', '), "]"))
            .invoke();
    };
    TaskEntity.prototype.lock = function (taskIds) {
        return this.service.routeGenerator
            .post(Tasks_consts_1.Routes.LOCK_TASK)
            .withExtractor(Tasks_consts_1.successExtractor)
            .withPayload({ task_ids: taskIds })
            .setException("failed to lock the tasks [".concat(taskIds.join(', '), "]"))
            .invoke();
    };
    TaskEntity.prototype.duplicate = function (taskId) {
        return this.service.routeGenerator
            .post(Tasks_consts_1.Routes.DUPLICATE_TASK)
            .withExtractor(Tasks_consts_1.taskExtractor)
            .withPayload({ id: taskId })
            .setException("failed to duplicate task ".concat(taskId))
            .withRouteParams({ id: taskId })
            .invoke();
    };
    TaskEntity.prototype.submitForm = function (form) {
        return this.service.routeGenerator
            .post(Tasks_consts_1.Routes.FORM_SUBMIT)
            .withExtractor(Tasks_consts_1.formExtractor)
            .withRouteParams({ id: form.task_id, way_point_id: form.way_point_id })
            .withPayload(form)
            .setException('failed to submit form')
            .invoke();
    };
    TaskEntity.prototype.getLocations = function (id) {
        return this.service.routeGenerator
            .get(Tasks_consts_1.Routes.GET_TASK_LOCATIONS)
            .withExtractor(Tasks_consts_1.locationExtractor)
            .withRouteParams({ id: id })
            .setException("failed to get location of the task ".concat(id))
            .invoke();
    };
    TaskEntity.prototype.changeTeam = function (id, teamId) {
        return this.service.routeGenerator
            .post(Tasks_consts_1.Routes.CHANGE_TASK_TEAM)
            .withExtractor(Tasks_consts_1.successExtractor)
            .withPayload({ id: id, team_id: teamId })
            .setException("failed to change the team of task ".concat(id))
            .invoke();
    };
    TaskEntity.prototype.activityLog = function (id) {
        return this.service.routeGenerator
            .get(Tasks_consts_1.Routes.GET_TASK_ACTIVITY_LOG)
            .withExtractor(Tasks_consts_1.defaultExtractor)
            .withRouteParams({ id: id })
            .setException("failed to get activity log for task ".concat(id))
            .invoke();
    };
    TaskEntity.prototype.closedTaskByQuery = function (query, page, limit) {
        return this.service.routeGenerator
            .get(Tasks_consts_1.Routes.GET_CLOSED_TASKS_WITH_QUERY)
            .withExtractor(Tasks_consts_1.defaultExtractor)
            .withQueryString({ query: query, page: page, limit: limit })
            .setException("failed to get closed tasks with query ".concat(query))
            .invoke();
    };
    TaskEntity.prototype.getHistoryTasks = function (query, page, limit) {
        return this.service.routeGenerator
            .get(Tasks_consts_1.Routes.GET_HISTORY_TASKS)
            .withExtractor(Tasks_consts_1.defaultExtractor)
            .withQueryString({ query: query, page: page, limit: limit })
            .setException("failed to get history tasks with query ".concat(query))
            .invoke();
    };
    TaskEntity.prototype.getHistoryTasksMetadata = function (query) {
        return this.service.routeGenerator
            .get(Tasks_consts_1.Routes.GET_HISTORY_TASKS_METADATA)
            .withExtractor(Tasks_consts_1.defaultExtractor)
            .withQueryString({ query: query })
            .setException("failed to get history tasks count with query ".concat(query))
            .invoke();
    };
    TaskEntity.prototype.cancelAllOpen = function () {
        return this.service.routeGenerator
            .post(Tasks_consts_1.Routes.CANCEL_ALL_OPEN_TASKS)
            .withExtractor(Tasks_consts_1.successExtractor)
            .setException('failed to to cancel all open tasks')
            .invoke();
    };
    TaskEntity.prototype.updatePreparationStatus = function (taskId, preparationStatus) {
        return __awaiter(this, void 0, void 0, function () {
            var task;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.service.routeGenerator
                            .post(Tasks_consts_1.Routes.UPDATE_TASK_PREPARATION_STATUS)
                            .withExtractor(Tasks_consts_1.taskExtractor)
                            .setException("failed to update preparation status taskId: ".concat(taskId, ", status: ").concat(preparationStatus))
                            .withPayload({ task_id: taskId, preparation_status: preparationStatus })
                            .invoke()];
                    case 1:
                        task = _a.sent();
                        return [2 /*return*/, this.addOrUpdateTask(task)];
                }
            });
        });
    };
    TaskEntity.prototype.massCancel = function (taskIds, reasonId, text, automaticallyCancelled) {
        return this.service.routeGenerator
            .post(Tasks_consts_1.Routes.MASS_TASK_CANCEL)
            .withExtractor(Tasks_consts_1.successExtractor)
            .setException("failed to cancel tasks [".concat(taskIds.join(', '), "]"))
            .withPayload({ task_ids: taskIds, reason: reasonId, text: text, automatically_cancelled: automaticallyCancelled })
            .invoke();
    };
    TaskEntity.prototype.releaseToDrivers = function (ids) {
        return this.service.routeGenerator
            .post(Tasks_consts_1.Routes.RELEASE_TASKS_TO_DRIVERS)
            .withExtractor(Tasks_consts_1.successExtractor)
            .setException("failed to release tasks [".concat(ids.join(', '), "] to drivers"))
            .withPayload({ ids: ids })
            .invoke();
    };
    TaskEntity.prototype.moveToPlanning = function (task_ids) {
        return this.service.routeGenerator
            .post(Tasks_consts_1.Routes.MOVE_TASKS_TO_PLANNING)
            .withExtractor(Tasks_consts_1.successExtractor)
            .setException("failed to move tasks [".concat(task_ids.join(', '), "] to planning"))
            .withPayload({ task_ids: task_ids })
            .invoke();
    };
    TaskEntity.prototype.massUnassign = function (task_ids, options) {
        return this.service.routeGenerator
            .post(Tasks_consts_1.Routes.MASS_TASK_UNASSIGN)
            .withExtractor(Tasks_consts_1.successExtractor)
            .setException("failed to unassign tasks ".concat(task_ids.join(', ')))
            .withPayload({ task_ids: task_ids, options: options })
            .invoke();
    };
    TaskEntity.prototype.massAssign = function (user_id, task_ids, options, targetRun) {
        return this.service.routeGenerator
            .post(Tasks_consts_1.Routes.MASS_TASK_ASSIGN)
            .withExtractor(Tasks_consts_1.successExtractor)
            .setException("failed to assign tasks ".concat(task_ids.join(', '), " to user ").concat(user_id))
            .withPayload({ user_id: user_id, task_ids: task_ids, options: options, target_run: targetRun })
            .invoke();
    };
    TaskEntity.prototype.batchGet = function (ids) {
        return __awaiter(this, void 0, void 0, function () {
            var tasks;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.service.routeGenerator
                            .get(Tasks_consts_1.Routes.BATCH_GET_TASK)
                            .withExtractor(Tasks_consts_1.tasksExtractor)
                            .setException("failed to fetch tasks ids - ".concat(ids.toString()))
                            .withQueryString({ ids: ids })
                            .invoke()];
                    case 1:
                        tasks = _a.sent();
                        tasks.map(function (task) { return _this.addOrUpdateTask(task); });
                        return [2 /*return*/, tasks];
                }
            });
        });
    };
    TaskEntity.prototype.get = function (id) {
        return this.getOrFetch(id, Tasks_consts_1.defaultExtractor, Tasks_consts_1.defaultExtractor);
    };
    TaskEntity.prototype.forceGet = function (id) {
        return this.fetchAndStore(id, Tasks_consts_1.defaultExtractor, Tasks_consts_1.defaultExtractor);
    };
    TaskEntity.prototype.acknowledge = function (id) {
        return __awaiter(this, void 0, void 0, function () {
            var updatedTask;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.service.routeGenerator
                            .post(Tasks_consts_1.Routes.ACKNOWLEDGE_TASK)
                            .withExtractor(Tasks_consts_1.taskExtractor)
                            .setException("failed to acknowledge task - ".concat(id))
                            .withPayload({ task_id: id })
                            .invoke()];
                    case 1:
                        updatedTask = _a.sent();
                        return [2 /*return*/, this.addOrUpdateTask(updatedTask)];
                }
            });
        });
    };
    TaskEntity.prototype.cancel = function (id) {
        return __awaiter(this, void 0, void 0, function () {
            var updatedTask;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.service.routeGenerator
                            .post(Tasks_consts_1.Routes.CANCEL_TASK)
                            .withExtractor(Tasks_consts_1.defaultExtractor)
                            .setException("failed to cancel task - ".concat(id))
                            .withRouteParams({ id: id })
                            .invoke()];
                    case 1:
                        updatedTask = _a.sent();
                        return [2 /*return*/, this.addOrUpdateTask(updatedTask)];
                }
            });
        });
    };
    TaskEntity.prototype.finish = function (id) {
        return __awaiter(this, void 0, void 0, function () {
            var updatedTask;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.service.routeGenerator
                            .post(Tasks_consts_1.Routes.FINISH_TASK)
                            .withExtractor(Tasks_consts_1.defaultExtractor)
                            .setException("failed to finish task - ".concat(id))
                            .withRouteParams({ id: id })
                            .invoke()];
                    case 1:
                        updatedTask = _a.sent();
                        return [2 /*return*/, this.addOrUpdateTask(updatedTask)];
                }
            });
        });
    };
    TaskEntity.prototype.getPlanningTasks = function (options) {
        return this.handleTasksRequest(Tasks_consts_1.Routes.GET_PLANNING_TASKS, options);
    };
    TaskEntity.prototype.getOpenTasks = function (options) {
        return this.handleTasksRequest(Tasks_consts_1.Routes.GET_OPEN_TASKS, options);
    };
    TaskEntity.prototype.getOpenTasksKeySetPagination = function (options) {
        return this.handleTasksKeySetPaginationRequest(Tasks_consts_1.Routes.GET_OPEN_TASKS, options);
    };
    TaskEntity.prototype.getInvalidTasks = function () {
        return this.handleTasksRequest(Tasks_consts_1.Routes.GET_INVALID_TASKS);
    };
    TaskEntity.prototype.updatePriorities = function (tasksPriorities) {
        return this.service.routeGenerator
            .patch(Tasks_consts_1.Routes.UPDATE_TASKS_PRIORITIES)
            .withExtractor(Tasks_consts_1.successExtractor)
            .setException("failed to update priority of tasks ".concat(tasksPriorities))
            .withPayload({ data: tasksPriorities })
            .invoke();
    };
    /* Public Helper Functions */
    TaskEntity.prototype.getTaskNotesByWayPoint = function (taskId, waypointId) {
        var task = this.store.getItem(taskId);
        var taskNotes = (0, lodash_1.filter)(task.task_notes, function (taskNote) { return taskNote.type === types_1.NoteType.TaskNote && taskNote.way_point_id === waypointId; });
        return taskNotes;
    };
    TaskEntity.prototype.getTaskInventoriesByWayPoint = function (taskId, waypointId) {
        var task = this.store.getItem(taskId);
        var wayPointInventories = (0, lodash_1.filter)(task === null || task === void 0 ? void 0 : task.task_inventories, function (taskInventory) { return taskInventory.way_point_id === waypointId; });
        var taskInventories = (0, lodash_1.map)(wayPointInventories, function (taskInventory) {
            taskInventory.inventories = (0, lodash_1.filter)(wayPointInventories, function (wayPointInventory) { return wayPointInventory.parent_task_inventory_id == taskInventory.id; });
            return taskInventory;
        });
        return taskInventories.filter(function (inventory) { return (0, lodash_1.isNil)(inventory.parent_task_inventory_id); });
    };
    /*********/
    TaskEntity.prototype.attachSubscriptions = function () {
        this.realTime.on(Tasks_consts_1.TaskRealTimeEvents.TASK_UPDATE, this.onUpdateTask);
        this.registerOnWayPointAdded(this.onWayPointAdded);
        this.registerOnWayPointUpdate(this.onWayPointUpdate);
        this.registerOnWayPointDeleted(this.onWayPointDeleted);
        this.realTime.on(Tasks_consts_1.TaskRealTimeEvents.NEW_SCAN, this.onNewScanAdded);
        this.realTime.on(Tasks_consts_1.TaskRealTimeEvents.NEW_NOTE, this.onNewNoteAdded);
        this.realTime.on(Tasks_consts_1.TaskRealTimeEvents.TASK_DELETED, this.onTaskDelete);
        this.realTime.on(Tasks_consts_1.TaskRealTimeEvents.NEW_TASK, this.onNewTaskAdded);
    };
    return TaskEntity;
}(StoreEntity_1.default));
exports.default = TaskEntity;
//# sourceMappingURL=TaskEntity.js.map