"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.filterChecksByLabels = filterChecksByLabels;
exports.getConciseLabelState = void 0;
exports.getFilteredLabelsByChecks = getFilteredLabelsByChecks;
exports.getLabelFilters = getLabelFilters;
exports.getLabelKeys = void 0;
exports.getLabels = getLabels;
exports.separateLabelsByBooleanType = exports.groupLabelsByKey = void 0;

var _lodash = require("lodash");

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 _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 _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(_e2) { throw _e2; }, 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(_e3) { didErr = true; err = _e3; }, 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 getLabels(checks) {
  if (checks == null || typeof checks[Symbol.iterator] !== "function") {
    // eslint-disable-next-line no-console
    return {};
  }

  var labelMap = {};

  var _iterator = _createForOfIteratorHelper(checks),
      _step;

  try {
    for (_iterator.s(); !(_step = _iterator.n()).done;) {
      var check = _step.value;

      if (check.labels) {
        for (var _i = 0, _Object$entries = Object.entries(check.labels); _i < _Object$entries.length; _i++) {
          var _Object$entries$_i = _slicedToArray(_Object$entries[_i], 2),
              key = _Object$entries$_i[0],
              value = _Object$entries$_i[1];

          var id = "canary:".concat(key, ":").concat(value);
          labelMap[id] = {
            type: "canary",
            id: id,
            key: key,
            value: value,
            label: value === "true" ? key : "".concat(key, ": ").concat(value)
          };
        }
      }
    }
  } catch (err) {
    _iterator.e(err);
  } finally {
    _iterator.f();
  }

  return labelMap;
}

function getLabelFilters() {
  var stateful = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  var labels = arguments.length > 1 ? arguments[1] : undefined;
  var labelLen = Object.keys(labels).length;
  var filters = Object.entries(stateful).reduce(function (acc, _ref) {
    var _ref2 = _slicedToArray(_ref, 2),
        k = _ref2[0],
        v = _ref2[1];

    var exInsert = acc.exclude.length;
    var inInsert = acc.include.length;

    if (labelLen > 0 && labels[k] == null) {
      return acc;
    }

    if (v === -1) {
      acc.exclude[exInsert] = k;
    }

    if (v === 1) {
      acc.include[inInsert] = k;
    }

    return acc;
  }, {
    exclude: [],
    include: []
  });
  return filters;
}

var getLabelKeys = function getLabelKeys(labels) {
  return Array.from(_toConsumableArray(new Set(Object.keys(labels).map(function (label) {
    return label.match(/(?<=:)(.*?)(?=:)/g)[0];
  })))).reduce(function (acc, k) {
    acc[k] = null;
    return acc;
  }, {});
}; // filter checks based on exclusion/inclusion label filters
// exclusion has a higher priority, and is considered prior to inclusion


exports.getLabelKeys = getLabelKeys;

function filterChecksByLabels(checks, labelFilters) {
  var excludedLabels = labelFilters.exclude;
  var includedLabels = labelFilters.include;

  if (excludedLabels.length === 0 && includedLabels.length === 0) {
    return checks;
  }

  var filtered = checks.reduce(function (acc, check) {
    if ("labels" in check === false && includedLabels.length > 0) {
      // "labels: null" cannot be included
      return acc;
    }

    if ("labels" in check === false && includedLabels.length === 0) {
      // "labels: null" cannot be excluded
      acc[check.id] = check;
      return acc;
    }

    if ("labels" in check && Object.keys(check.labels).length === 0 && includedLabels.length === 0) {
      // "labels: {}" cannot be excluded
      acc[check.id] = check;
      return acc;
    }

    if ("labels" in check && Object.keys(check.labels).length > 0 && includedLabels.length >= 0) {
      var _Object$entries$reduc = Object.entries(check.labels).reduce(function (accum, _ref3) {
        var _ref4 = _slicedToArray(_ref3, 2),
            k = _ref4[0],
            v = _ref4[1];

        if (accum.hasExclusion === true) {
          return accum;
        }

        var id = "canary:".concat(k, ":").concat(v);

        if (excludedLabels.length > 0 && excludedLabels.includes(id) === true) {
          accum.hasExclusion = true;
          return accum;
        }

        if (includedLabels.length > 0 && includedLabels.includes(id) === true) {
          accum.hasInclusion = true;
          return accum;
        }

        return accum;
      }, {
        hasExclusion: false,
        hasInclusion: false
      }),
          hasExclusion = _Object$entries$reduc.hasExclusion,
          hasInclusion = _Object$entries$reduc.hasInclusion;

      if (hasInclusion && hasExclusion === false) {
        acc[check.id] = check;
      }

      if (includedLabels.length === 0 && hasExclusion === false) {
        acc[check.id] = check;
      }
    }

    return Object.values(acc);
  }, {});
  return filtered;
} // filter labels based on the currently available checks
// (only include labels present in current checks list)


function getFilteredLabelsByChecks(checks, allLabels) {
  var checkLabels = {};
  checks.forEach(function (check) {
    if ((0, _lodash.isNil)(check.labels)) {
      return;
    }

    (0, _lodash.forEach)(check.labels, function (v, k) {
      var id = "canary:".concat(k, ":").concat(v);
      checkLabels[id] = allLabels[id];
    });
  });
  return checkLabels;
}

var separateLabelsByBooleanType = function separateLabelsByBooleanType(labelList) {
  var boolean = [];
  var nonBoolean = [];
  labelList.forEach(function (label) {
    var v = label.value;

    if (typeof v === "boolean" || v === "true" || v === "false") {
      boolean.push(label);
    } else {
      nonBoolean.push(label);
    }
  });
  return [boolean, nonBoolean];
};

exports.separateLabelsByBooleanType = separateLabelsByBooleanType;

var getConciseLabelState = function getConciseLabelState(labelState) {
  var conciseLabelState = Object.entries(labelState).reduce(function (acc, _ref5) {
    var _ref6 = _slicedToArray(_ref5, 2),
        k = _ref6[0],
        v = _ref6[1];

    if (v !== 0) {
      acc[k] = v;
    }

    return acc;
  }, {});
  return conciseLabelState;
};

exports.getConciseLabelState = getConciseLabelState;

var groupLabelsByKey = function groupLabelsByKey(labels) {
  var result = {};
  labels.forEach(function (label) {
    var existing = result[label.key] || [];
    result[label.key] = [].concat(_toConsumableArray(existing), [label]);
  });
  return result;
};

exports.groupLabelsByKey = groupLabelsByKey;