"use strict";

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

var _immer = _interopRequireDefault(require("immer"));

var _isEqual = _interopRequireDefault(require("lodash/isEqual"));

var _writeLockfiles = require("../lockfiles/write-lockfiles");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function stripTasks(tasks, lockfile) {
  const taskIds = new Set(tasks.map(task => task.id));
  return (0, _immer.default)(lockfile, draft => {
    draft.setup = Object.entries(draft.setup).reduce((accumulator, [taskId, taskResult]) => {
      if (taskIds.has(taskId)) {
        accumulator[taskId] = taskResult;
      }

      return accumulator;
    }, {});
  });
}
/**
 * Removes unmanaged tasks from the coat local and global lockfiles.
 *
 * If a task is no longer specified by one of the extended templates of this
 * project, the task result should be removed to clean up the lockfiles.
 *
 * @param globalTasks Global tasks that are part of the current coat project
 * @param localTasks Local tasks that are part of the current coat project
 * @param context The context of the current coat project
 */


async function removeUnmanagedTasksFromLockfiles(globalTasks, localTasks, context) {
  const newGlobalLockfile = stripTasks(globalTasks, context.coatGlobalLockfile);
  const newLocalLockfile = stripTasks(localTasks, context.coatLocalLockfile);
  const promises = []; // Only write lockfiles if they have changed

  if (!(0, _isEqual.default)(newGlobalLockfile, context.coatGlobalLockfile)) {
    promises.push((0, _writeLockfiles.writeGlobalLockfile)(newGlobalLockfile, context));
  }

  if (!(0, _isEqual.default)(newLocalLockfile, context.coatLocalLockfile)) {
    promises.push((0, _writeLockfiles.writeLocalLockfile)(newLocalLockfile, context));
  }

  await Promise.all(promises);
  return (0, _immer.default)(context, draft => {
    draft.coatGlobalLockfile = newGlobalLockfile;
    draft.coatLocalLockfile = newLocalLockfile;
  });
}