"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.aggregate = aggregate;
exports.getAggregatedGroupedChecks = void 0;

var _lodash = require("lodash");

var _utils = require("./utils");

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }

function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }

function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

// if all check icons are similar in a given iconList, use that icon.
// if there are different icons, use a icon that indicate 'mixing'.
function aggregateIcon(iconList) {
  iconList = iconList.filter(function (icon) {
    return icon !== "";
  });

  if (iconList.length === 0) {
    return null;
  }

  var icon = iconList[0];

  for (var i = 0; i < iconList.length; i += 1) {
    if (iconList[i] !== icon) {
      icon = "multiple";
      break;
    }
  }

  return icon;
} // if all check types are similar in a given typeList, use that type.
// if there are different types, use a type that indicate 'mixing'.


function aggregateType(typeList) {
  typeList = typeList.filter(function (type) {
    return type !== "";
  });

  if (typeList.length === 0) {
    return null;
  }

  var type = typeList[0];

  for (var i = 0; i < typeList.length; i += 1) {
    if (typeList[i] !== type) {
      type = "multiple";
      break;
    }
  }

  return type;
} // calculate the average health of all checks with valid statuses
// returns a simplified list of statuses that indicates the overall health.


function aggregateStatuses(statusLists) {
  var count = (0, _lodash.reduce)(statusLists, function (sum, i) {
    return Math.max(sum, i == null ? 0 : i.length);
  }, 0);
  var aggregated = [];

  var _loop = function _loop(i) {
    var allPass = (0, _lodash.reduce)(statusLists, function (sum, list) {
      return sum && list != null && list.length >= i && list[i] && list[i].status;
    }, true);
    var allFail = (0, _lodash.reduce)(statusLists, function (sum, list) {
      return sum && list != null && list.length >= i && list[i] && !list[i].status;
    }, true);

    if (allPass) {
      aggregated.push({
        id: aggregated.length,
        status: true
      });
    } else if (allFail) {
      aggregated.push({
        id: aggregated.length,
        status: false
      });
    } else {
      aggregated.push({
        id: aggregated.length,
        mixed: true
      });
    }
  };

  for (var i = 0; i < count; i += 1) {
    _loop(i);
  }

  return aggregated;
} // The uptime for a group, is defined as the minimum uptime with the group
// eslint-disable-next-line no-unused-vars


function minUptime(items) {
  return (0, _lodash.reduce)(items, function (old, item) {
    if ((0, _utils.getPercentage)(old.uptime) > (0, _utils.getPercentage)(item.uptime)) {
      return item;
    }

    return old;
  }, {
    passed: 0,
    failed: 0
  });
} // The uptime for a group, is defined as the minimum uptime with the group


function sumUptime(items) {
  return (0, _lodash.reduce)(items, function (old, item) {
    old.passed += item.uptime.passed;
    old.failed += item.uptime.failed;
    return old;
  }, {
    passed: 0,
    failed: 0
  });
}

function avgLatency(items) {
  var total = (0, _lodash.reduce)(items, function (sum, i) {
    return sum + i.latency.rolling1h;
  }, 0);
  return total / items.length;
}

function aggregate(title, items) {
  if (items == null) {
    return {};
  }

  return {
    description: title,
    icon: aggregateIcon(items.map(function (item) {
      return item.icon;
    })),
    latency: {
      rolling1h: avgLatency(items)
    },
    uptime: sumUptime(items),
    checkStatuses: aggregateStatuses(items.map(function (item) {
      return item.checkStatuses;
    })),
    type: aggregateType(items.map(function (item) {
      return item.type;
    })),
    namespaces: _toConsumableArray(new Set(items.map(function (item) {
      return item.namespace;
    })))
  };
}

var getAggregatedGroupedChecks = function getAggregatedGroupedChecks(groupedChecks) {
  var groupSingleItems = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
  var aggregatedValue = Object.entries(groupedChecks).reduce(function (acc, _ref) {
    var _ref2 = _slicedToArray(_ref, 2),
        k = _ref2[0],
        v = _ref2[1];

    if (groupSingleItems || v.length > 1) {
      var aggregated = _objectSpread(_objectSpread({}, aggregate(k, v)), {}, {
        isAggregate: true,
        subRows: v,
        name: k
      });

      acc[k] = aggregated;
    } else if (v.length > 0) {
      var check = v[0];
      acc[k] = check;
    }

    return acc;
  }, {});
  return aggregatedValue;
};

exports.getAggregatedGroupedChecks = getAggregatedGroupedChecks;