"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getPanelLayoutsAreEqual = exports.defaultDiffFunction = exports.areTimesEqual = void 0;
var _lodash = require("lodash");
var _moment = _interopRequireDefault(require("moment"));
var _fastDeepEqual = _interopRequireDefault(require("fast-deep-equal"));
/*
 * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
 * or more contributor license agreements. Licensed under the Elastic License
 * 2.0 and the Server Side Public License, v 1; you may not use this file except
 * in compliance with, at your election, the Elastic License 2.0 or the Server
 * Side Public License, v 1.
 */

const convertTimeToUTCString = time => {
  if ((0, _moment.default)(time).isValid()) {
    return (0, _moment.default)(time).utc().format('YYYY-MM-DDTHH:mm:ss.SSS[Z]');
  } else {
    // If it's not a valid moment date, then it should be a string representing a relative time
    // like 'now' or 'now-15m'.
    return time;
  }
};
const areTimesEqual = (timeA, timeB) => {
  return convertTimeToUTCString(timeA) === convertTimeToUTCString(timeB);
};
exports.areTimesEqual = areTimesEqual;
const defaultDiffFunction = (a, b) => (0, _fastDeepEqual.default)(a, b);

/**
 * Checks whether the panel maps have the same keys, and if they do, whether all of the other keys inside each panel
 * are equal. Skips explicit input as that needs to be handled asynchronously.
 */
exports.defaultDiffFunction = defaultDiffFunction;
const getPanelLayoutsAreEqual = (originalPanels, newPanels) => {
  const originalEmbeddableIds = Object.keys(originalPanels);
  const newEmbeddableIds = Object.keys(newPanels);
  const embeddableIdDiff = (0, _lodash.xor)(originalEmbeddableIds, newEmbeddableIds);
  if (embeddableIdDiff.length > 0) {
    return false;
  }
  const commonPanelDiff = (originalObj, newObj) => {
    const differences = {};
    const keys = [...new Set([...Object.keys(originalObj), ...Object.keys(newObj)])];
    for (const key of keys) {
      if (key === undefined) continue;
      if (!defaultDiffFunction(originalObj[key], newObj[key])) differences[key] = newObj[key];
    }
    return differences;
  };
  for (const embeddableId of newEmbeddableIds) {
    const {
      explicitInput: originalExplicitInput,
      panelRefName: panelRefA,
      ...commonPanelDiffOriginal
    } = originalPanels[embeddableId];
    const {
      explicitInput: newExplicitInput,
      panelRefName: panelRefB,
      ...commonPanelDiffNew
    } = newPanels[embeddableId];
    if (!(0, _lodash.isEmpty)(commonPanelDiff(commonPanelDiffOriginal, commonPanelDiffNew))) return false;
  }
  return true;
};
exports.getPanelLayoutsAreEqual = getPanelLayoutsAreEqual;