"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.gatherAllTasks = gatherAllTasks;

var _coatManifestTasks = require("../types/coat-manifest-tasks");

function mergeTasks(tasks) {
  // If multiple tasks share the same id, the latest task
  // to use the id should replace the earliest task in the array
  return tasks.reduce((accumulator, task) => {
    const savedTaskIndex = accumulator.findIndex(savedTask => savedTask.id === task.id);

    if (savedTaskIndex === -1) {
      // Task does not exist yet, save it in the resulting array
      accumulator.push(task);
    } else {
      // Replace earlier task with current task version
      accumulator[savedTaskIndex] = task;
    }

    return accumulator;
  }, []);
}
/**
 * Gathers all global and local tasks from the current coat project and returns
 * them sorted with global tasks before local tasks.
 *
 * Tasks with the same id and global/local scope will be merged, in that a
 * task replace its earlier version if it has the same id and takes its place
 * in the resulting tasks array.
 *
 * @param allTemplates All extended templates from the current coat project
 */


function gatherAllTasks(allTemplates) {
  // Gather all tasks from the extended templates
  const {
    globalTasks,
    localTasks
  } = allTemplates.reduce((result, template) => {
    result.globalTasks.push(...template.setup.filter(task => !task.local) // The local property is destructured to remove it from the
    // resulting task
    //
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    .map(({
      local,
      ...task
    }) => ({ ...task,
      type: _coatManifestTasks.CoatTaskType.Global
    })));
    result.localTasks.push(...template.setup.filter(task => !!task.local) // The local property is destructured to remove it from the
    // resulting task
    //
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    .map(({
      local,
      ...task
    }) => ({ ...task,
      type: _coatManifestTasks.CoatTaskType.Local
    })));
    return result;
  }, {
    globalTasks: [],
    localTasks: []
  }); // Merge tasks with the same id

  const mergedGlobalTasks = mergeTasks(globalTasks);
  const mergedLocalTasks = mergeTasks(localTasks);
  return [...mergedGlobalTasks, ...mergedLocalTasks];
}