"use strict";

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

var _lodash = require("lodash");

var _qs = require("qs");

var _axios = require("../axios");

function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }

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 _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 _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }

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 _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; }

function compareStatus(a, b) {
  if (a.status === b.status) {
    return 0;
  }

  if (a.status === "unhealthy") {
    return -1;
  }

  return 1;
}

function unroll(topology, depth) {
  if (topology == null) {
    return [];
  }

  topology = (0, _lodash.flattenDepth)([topology], 3);

  if (depth === 0) {
    return topology;
  }

  var items = [];

  if ((0, _lodash.isArray)(topology)) {
    if (topology.type !== "summary") {
      items.push(topology);
    }

    var _iterator = _createForOfIteratorHelper(topology),
        _step;

    try {
      for (_iterator.s(); !(_step = _iterator.n()).done;) {
        var item = _step.value;
        items.push.apply(items, _toConsumableArray(unroll(item.components, depth - 1)));
      }
    } catch (err) {
      _iterator.e(err);
    } finally {
      _iterator.f();
    }
  }

  items.sort(function (a, b) {
    var status = compareStatus(a, b);

    if (status !== 0) {
      return status;
    }

    return a.name > b.name;
  });
  var flattened = (0, _lodash.flattenDepth)(items, 3);

  if ((0, _lodash.isEmpty)(flattened.id) && flattened.components != null && flattened.components.length === 1) {
    return flattened.components[0];
  }

  return flattened;
}

var getTopology = /*#__PURE__*/function () {
  var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(params) {
    var query;
    return regeneratorRuntime.wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            query = (0, _qs.stringify)(params);
            return _context.abrupt("return", _axios.CanaryChecker.get("/api/topology?".concat(query)).then(function (results) {
              var depth = query === "" ? 0 : 2;

              if (params.depth != null) {
                depth = params.depth;
              }

              var data = results.data;

              if (data.length === 2 && (0, _lodash.isEmpty)(data[0].id)) {
                data = [data[1]];
              }

              return {
                data: unroll(data, depth, false)
              };
            }));

          case 2:
          case "end":
            return _context.stop();
        }
      }
    }, _callee);
  }));

  return function getTopology(_x) {
    return _ref.apply(this, arguments);
  };
}();

exports.getTopology = getTopology;

var getCanaries = /*#__PURE__*/function () {
  var _ref2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(params) {
    var query;
    return regeneratorRuntime.wrap(function _callee2$(_context2) {
      while (1) {
        switch (_context2.prev = _context2.next) {
          case 0:
            query = (0, _qs.stringify)(params);
            return _context2.abrupt("return", _axios.CanaryChecker.get("/api?".concat(query)));

          case 2:
          case "end":
            return _context2.stop();
        }
      }
    }, _callee2);
  }));

  return function getCanaries(_x2) {
    return _ref2.apply(this, arguments);
  };
}();

exports.getCanaries = getCanaries;