"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getEarlyRecoveredAlerts = getEarlyRecoveredAlerts;
exports.trimRecoveredAlerts = trimRecoveredAlerts;
var _lodash = require("lodash");
/*
 * 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; you may not use this file except in compliance with the Elastic License
 * 2.0.
 */

function trimRecoveredAlerts(logger, recoveredAlerts = {}, maxAlerts) {
  const alerts = (0, _lodash.map)(recoveredAlerts, (value, key) => {
    return {
      key,
      flappingHistory: value.getFlappingHistory() || []
    };
  });
  const earlyRecoveredAlertOpts = getEarlyRecoveredAlerts(logger, alerts, maxAlerts);
  const earlyRecoveredAlerts = {};
  earlyRecoveredAlertOpts.forEach(opt => {
    const alert = recoveredAlerts[opt.key];
    alert.setFlapping(false);
    earlyRecoveredAlerts[opt.key] = recoveredAlerts[opt.key];
    delete recoveredAlerts[opt.key];
  });
  return {
    trimmedAlertsRecovered: recoveredAlerts,
    earlyRecoveredAlerts
  };
}
function getEarlyRecoveredAlerts(logger, recoveredAlerts, maxAlerts) {
  let earlyRecoveredAlerts = [];
  if (recoveredAlerts.length > maxAlerts) {
    recoveredAlerts.sort((a, b) => {
      return a.flappingHistory.length - b.flappingHistory.length;
    });
    earlyRecoveredAlerts = recoveredAlerts.slice(maxAlerts);
    logger.warn(`Recovered alerts have exceeded the max alert limit of ${maxAlerts} : dropping ${earlyRecoveredAlerts.length} ${earlyRecoveredAlerts.length > 1 ? 'alerts' : 'alert'}.`);
  }
  return earlyRecoveredAlerts;
}