"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.Cell = Cell;
exports.HealthCell = HealthCell;
exports.LatencyCell = LatencyCell;
exports.TitleCell = TitleCell;
exports.UptimeCell = UptimeCell;
exports.getColumns = getColumns;
exports.getSortType = getSortType;
exports.makeColumnsForPivot = makeColumnsForPivot;

var _sorting = require("./sorting");

var _renderers = require("../renderers");

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

var _data = require("../data");

var _Badge = require("../../Badge");

var _indexModule = _interopRequireDefault(require("../index.module.css"));

var _jsxRuntime = require("react/jsx-runtime");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); 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 = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : 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 _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(_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 Cell(_ref) {
  var state = _ref.state,
      value = _ref.value,
      row = _ref.row,
      column = _ref.column;
  var pivotCellType = state.pivotCellType;

  if (column.id === "name") {
    return TitleCell({
      row: row
    });
  }

  if (pivotCellType === "uptime" || column.id === "uptime") {
    var _value$uptime;

    if (value == null) {
      return _renderers.empty;
    }

    var newValue = (_value$uptime = value === null || value === void 0 ? void 0 : value.uptime) !== null && _value$uptime !== void 0 ? _value$uptime : value;
    return UptimeCell({
      value: newValue
    });
  }

  if (pivotCellType === "checkStatuses" || column.id === "checkStatuses") {
    var _value$checkStatuses;

    if (value == null) {
      return _renderers.empty;
    }

    var _newValue = (_value$checkStatuses = value === null || value === void 0 ? void 0 : value.checkStatuses) !== null && _value$checkStatuses !== void 0 ? _value$checkStatuses : value;

    return HealthCell({
      value: _newValue
    });
  }

  if (pivotCellType === "latency" || column.id === "latency") {
    var _value$latency;

    if (value == null) {
      return _renderers.empty;
    }

    var _newValue2 = (_value$latency = value === null || value === void 0 ? void 0 : value.latency) !== null && _value$latency !== void 0 ? _value$latency : value;

    return LatencyCell({
      value: _newValue2
    });
  }

  return null;
}

function HealthCell(_ref2) {
  var value = _ref2.value;
  return /*#__PURE__*/(0, _jsxRuntime.jsx)(_renderers.StatusList, {
    checkStatuses: value
  });
}

function UptimeCell(_ref3) {
  var value = _ref3.value;
  return /*#__PURE__*/(0, _jsxRuntime.jsx)(_renderers.Percentage, {
    upper: value.passed + value.failed,
    lower: value.passed
  });
}

function LatencyCell(_ref4) {
  var value = _ref4.value;
  return /*#__PURE__*/(0, _jsxRuntime.jsx)(_renderers.Duration, {
    ms: value.p95
  });
}

function TitleCell(_ref5) {
  var _row$original, _row$original$row$ori;

  var row = _ref5.row;
  var rowValues = ((_row$original = row.original) === null || _row$original === void 0 ? void 0 : _row$original.pivoted) === true ? (_row$original$row$ori = row.original[row.original.valueLookup]) !== null && _row$original$row$ori !== void 0 ? _row$original$row$ori : null : row.original;
  var title = (0, _data.GetName)(rowValues);

  if (row.hideNamespacePrefix) {
    title = (0, _utils.removeNamespacePrefix)(title, rowValues);
  }

  return /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
    className: _indexModule.default.checkTitleRow,
    children: /*#__PURE__*/(0, _jsxRuntime.jsxs)("span", {
      className: "flex flex-row items-center",
      style: {
        paddingLeft: "".concat(row.depth * 1.1, "rem")
      },
      children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_renderers.Title, {
        title: title,
        icon: rowValues.icon || rowValues.type
      }), row.canExpand && rowValues.subRows && (rowValues === null || rowValues === void 0 ? void 0 : rowValues.subRows.length) > 1 && /*#__PURE__*/(0, _jsxRuntime.jsx)("span", {
        className: "ml-1 flex items-center",
        children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_Badge.Badge, {
          className: "ml-1",
          colorClass: "bg-gray-200 text-gray-800",
          roundedClass: "rounded-xl",
          text: rowValues === null || rowValues === void 0 ? void 0 : rowValues.subRows.length,
          size: "xs"
        })
      }), row.showNamespaceTags ? rowValues.namespaces ? /*#__PURE__*/(0, _jsxRuntime.jsx)(_Badge.Badge, {
        className: "ml-2",
        text: "".concat(rowValues.namespaces[0]).concat(rowValues.namespaces.length > 1 ? ", ..." : ""),
        title: rowValues.namespaces.length > 1 ? rowValues.namespaces.join(", ") : null,
        size: "xs"
      }) : rowValues.namespace ? /*#__PURE__*/(0, _jsxRuntime.jsx)(_Badge.Badge, {
        className: "ml-2",
        text: rowValues.namespace,
        size: "xs"
      }) : null : null]
    })
  });
}

function getSortString(original) {
  var _original$sortKey, _original$namespace;

  // case insensitive name sorting, with namespace as a secondary sort
  var sortString = "".concat((_original$sortKey = original.sortKey) === null || _original$sortKey === void 0 ? void 0 : _original$sortKey.toLowerCase()).concat((_original$namespace = original.namespace) === null || _original$namespace === void 0 ? void 0 : _original$namespace.toLowerCase());
  return sortString;
}

function getPivotSortValueOrDefault(a, b, pivotAccessor) {
  var _a$original4, _ref8, _a$original$pivotAcce, _b$original4, _ref9, _b$original$pivotAcce;

  if (pivotAccessor === "name") {
    var _a$original, _ref6, _a$original$a$origina, _a$original2, _a$original3, _b$original, _ref7, _b$original$b$origina, _b$original2, _b$original3;

    var _aValue = ((_a$original = a.original) === null || _a$original === void 0 ? void 0 : _a$original.pivoted) === true ? (_ref6 = (_a$original$a$origina = a === null || a === void 0 ? void 0 : a.original[a === null || a === void 0 ? void 0 : (_a$original2 = a.original) === null || _a$original2 === void 0 ? void 0 : _a$original2.valueLookup]) !== null && _a$original$a$origina !== void 0 ? _a$original$a$origina : a === null || a === void 0 ? void 0 : (_a$original3 = a.original) === null || _a$original3 === void 0 ? void 0 : _a$original3.aggregate) !== null && _ref6 !== void 0 ? _ref6 : undefined : a === null || a === void 0 ? void 0 : a.original;

    var _bValue = (b === null || b === void 0 ? void 0 : (_b$original = b.original) === null || _b$original === void 0 ? void 0 : _b$original.pivoted) === true ? (_ref7 = (_b$original$b$origina = b === null || b === void 0 ? void 0 : b.original[b === null || b === void 0 ? void 0 : (_b$original2 = b.original) === null || _b$original2 === void 0 ? void 0 : _b$original2.valueLookup]) !== null && _b$original$b$origina !== void 0 ? _b$original$b$origina : b === null || b === void 0 ? void 0 : (_b$original3 = b.original) === null || _b$original3 === void 0 ? void 0 : _b$original3.aggregate) !== null && _ref7 !== void 0 ? _ref7 : undefined : b === null || b === void 0 ? void 0 : b.original;

    return {
      aValue: _aValue,
      bValue: _bValue
    };
  }

  var aValue = ((_a$original4 = a.original) === null || _a$original4 === void 0 ? void 0 : _a$original4.pivoted) === true ? (_ref8 = (_a$original$pivotAcce = a.original[pivotAccessor]) !== null && _a$original$pivotAcce !== void 0 ? _a$original$pivotAcce : a.original.aggregate) !== null && _ref8 !== void 0 ? _ref8 : undefined : a.original;
  var bValue = ((_b$original4 = b.original) === null || _b$original4 === void 0 ? void 0 : _b$original4.pivoted) === true ? (_ref9 = (_b$original$pivotAcce = b.original[pivotAccessor]) !== null && _b$original$pivotAcce !== void 0 ? _b$original$pivotAcce : b.original.aggregate) !== null && _ref9 !== void 0 ? _ref9 : undefined : b.original;
  return {
    aValue: aValue,
    bValue: bValue
  };
}

function getSortType(pivotCellTypeOrAccessor, pivotAccessor) {
  var _sortTypes$pivotCellT;

  var sortTypes = {
    latency: function latency(a, b) {
      var _getPivotSortValueOrD = getPivotSortValueOrDefault(a, b, pivotAccessor),
          aValue = _getPivotSortValueOrD.aValue,
          bValue = _getPivotSortValueOrD.bValue;

      return (0, _sorting.getLatency)(aValue) < (0, _sorting.getLatency)(bValue) ? -1 : 1;
    },
    uptime: function uptime(a, b) {
      var _getPivotSortValueOrD2 = getPivotSortValueOrDefault(a, b, pivotAccessor),
          aValue = _getPivotSortValueOrD2.aValue,
          bValue = _getPivotSortValueOrD2.bValue;

      return (0, _sorting.getUptimeScore)(aValue) < (0, _sorting.getUptimeScore)(bValue) ? 1 : -1;
    },
    checkStatuses: function checkStatuses(a, b) {
      var _getPivotSortValueOrD3 = getPivotSortValueOrDefault(a, b, pivotAccessor),
          aValue = _getPivotSortValueOrD3.aValue,
          bValue = _getPivotSortValueOrD3.bValue;

      return (0, _sorting.getHealthPercentageScore)(aValue) < (0, _sorting.getHealthPercentageScore)(bValue) ? 1 : -1;
    },
    name: function name(a, b) {
      var _getPivotSortValueOrD4 = getPivotSortValueOrDefault(a, b, pivotAccessor),
          aValue = _getPivotSortValueOrD4.aValue,
          bValue = _getPivotSortValueOrD4.bValue;

      return getSortString(aValue) < getSortString(bValue) ? -1 : 1;
    }
  };
  return pivotAccessor === "name" ? sortTypes[pivotAccessor] : (_sortTypes$pivotCellT = sortTypes[pivotCellTypeOrAccessor]) !== null && _sortTypes$pivotCellT !== void 0 ? _sortTypes$pivotCellT : "alphanumeric";
}

function makeColumnsForPivot() {
  var _ref10 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
      pivotSet = _ref10.pivotSet,
      pivotCellType = _ref10.pivotCellType,
      firstColumns = _ref10.firstColumns,
      _ref10$cellClass = _ref10.cellClass,
      cellClass = _ref10$cellClass === void 0 ? "px-5 py-2" : _ref10$cellClass;

  // For syntax https://stackoverflow.com/a/26578323/15581317
  var columns = [];

  var _iterator = _createForOfIteratorHelper(pivotSet.entries()),
      _step;

  try {
    for (_iterator.s(); !(_step = _iterator.n()).done;) {
      var _step$value = _slicedToArray(_step.value, 2),
          value = _step$value[1];

      columns[columns.length] = {
        Header: value.replace("piv0t-", ""),
        accessor: value,
        cellClass: cellClass,
        Cell: Cell,
        sortType: pivotCellType != null ? getSortType(pivotCellType, value) : "alphanumeric"
      };
    }
  } catch (err) {
    _iterator.e(err);
  } finally {
    _iterator.f();
  }

  var firsts = getColumns({
    columnObject: firstColumns,
    pivotCellType: pivotCellType
  });
  return [].concat(_toConsumableArray(firsts), columns);
}

function getColumns(_ref11) {
  var columnObject = _ref11.columnObject,
      _ref11$pivotCellType = _ref11.pivotCellType,
      pivotCellType = _ref11$pivotCellType === void 0 ? null : _ref11$pivotCellType;
  return Object.entries(columnObject).reduce(function (acc, _ref12, i) {
    var _ref13 = _slicedToArray(_ref12, 2),
        k = _ref13[0],
        v = _ref13[1];

    var Header = v.Header,
        accessor = v.accessor,
        cellClass = v.cellClass,
        IncomingCell = v.Cell,
        id = v.id;
    var pivotAccessor = accessor == null || typeof accessor === "function" ? id == null ? k : id : accessor;
    acc[i] = _objectSpread(_objectSpread(_objectSpread(_objectSpread({}, id != null && {
      id: id
    }), id == null && typeof accessor === "function" && {
      id: k
    }), accessor != null && {
      accessor: accessor
    }), {}, {
      Header: Header !== null && Header !== void 0 ? Header : function () {
        return null;
      },
      cellClass: cellClass !== null && cellClass !== void 0 ? cellClass : "px-5 py-2",
      Cell: IncomingCell !== null && IncomingCell !== void 0 ? IncomingCell : Cell,
      sortType: pivotCellType != null ? getSortType(pivotCellType, pivotAccessor) : accessor != null ? getSortType(accessor, pivotAccessor) : "alphanumeric"
    });
    return acc;
  }, []);
}