"use strict";

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

var _mergeWith = _interopRequireDefault(require("lodash/mergeWith"));

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

var _immer = require("immer");

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

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

function mergeWithArrayReplacement(source, target) {
  // Replace arrays rather than merging them
  if (Array.isArray(target) && Array.isArray(source)) {
    return target;
  }
}
/**
 * Updates both lockfiles and returns an updated coat context
 * that contains the new lockfile content
 *
 * @param options.updatedGlobalLockfile New global lockfile properties,
 * will be merged with the current global lockfile
 * @param options.updatedLocalLockfile New local lockfile properties,
 * will be merged with the current local lockfile
 * @param options.context The current coat context
 */


async function updateLockfiles({
  updatedGlobalLockfile,
  updatedLocalLockfile,
  context
}) {
  const mergedGlobalLockfile = (0, _mergeWith.default)({}, context.coatGlobalLockfile, updatedGlobalLockfile, mergeWithArrayReplacement);
  const mergedLocalLockfile = (0, _mergeWith.default)({}, context.coatLocalLockfile, updatedLocalLockfile, mergeWithArrayReplacement);
  const promises = [];

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

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

  await Promise.all(promises); // Return a new coat context with the updated lockfiles

  return (0, _immer.produce)(context, draft => {
    draft.coatGlobalLockfile = mergedGlobalLockfile;
    draft.coatLocalLockfile = mergedLocalLockfile;
  });
}