"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.taskMerger = void 0;
var merge_mapper_1 = require("../../Data/merge-mapper");
function hasNoActualChanges(diffArray) {
    if (!Array.isArray(diffArray)) {
        return false;
    }
    return diffArray.every(function (item) {
        if (item === undefined || item === null) {
            return true;
        }
        if (typeof item === 'object') {
            return Object.keys(item).length === 0;
        }
        return false;
    });
}
var removeInventories = function (result, isTaskNewFromRealtimeEvent, hasInventoriesInStore) {
    var noDiffOnInventories = result.diff &&
        result.diff.task_inventories &&
        hasNoActualChanges(result.diff.task_inventories) &&
        !hasInventoriesInStore;
    if (noDiffOnInventories || isTaskNewFromRealtimeEvent) {
        delete result.current.task_inventories;
    }
    return result;
};
var LOAD_ACTIONS = ['load', 'loadPlanningTasks', 'loadOpenTasks', 'loadInvalid'];
function mergeTaskIntoExisting(_a) {
    var tasksStore = _a.tasksStore, task = _a.task, params = _a.params;
    var way_points = task.way_points;
    if (way_points) {
        way_points.sort(function (wp1, wp2) { return wp1.position - wp2.position; });
    }
    var existingTask = tasksStore.get(task.id);
    var hasInventoriesInStore = !!(existingTask === null || existingTask === void 0 ? void 0 : existingTask.task_inventories);
    var result = merge_mapper_1.mergeMapper.mergeIntoExisting(tasksStore, task);
    var isLoadAction = LOAD_ACTIONS.includes(params === null || params === void 0 ? void 0 : params.action);
    if (!isLoadAction) {
        var isTaskNewFromRealtimeEvent = !existingTask;
        return removeInventories(result, isTaskNewFromRealtimeEvent, hasInventoriesInStore);
    }
    return result;
}
exports.taskMerger = { mergeTaskIntoExisting: mergeTaskIntoExisting };
//# sourceMappingURL=task-merger.js.map