"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.CanaryTable = CanaryTable;
exports.Table = Table;

var _react = _interopRequireWildcard(require("react"));

var _ti = require("react-icons/ti");

var _reactTable = require("react-table");

var _aggregate = require("./aggregate");

var _grouping = require("./grouping");

var _Columns = require("./Columns");

var _url = require("./url");

var _columns = require("./Columns/columns");

var _lib = require("./Rows/lib");

var _useCheckSetEqualityForPreviousVsCurrent = require("../Hooks/useCheckSetEqualityForPreviousVsCurrent");

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

var _excluded = ["checks", "labels", "history", "onCheckClick", "showNamespaceTags", "hideNamespacePrefix", "groupSingleItems", "theadStyle"],
    _excluded2 = ["data", "columns", "labels", "history", "pivotCellType", "hasGrouping", "onUnexpandableRowClick", "showNamespaceTags", "hideNamespacePrefix", "theadStyle"];

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

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 _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 _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 _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }

function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }

var styles = {
  outerDivClass: "border-l border-r border-gray-300",
  topBgClass: "bg-red-500",
  tableClass: "min-w-full border-separate",
  theadClass: "bg-white z-10",
  theadRowClass: "z-10",
  theadHeaderClass: "px-5 py-4 text-left text-xs font-medium text-gray-500 uppercase tracking-wider border-b border-gray-300",
  tbodyClass: "mt-4 rounded-md",
  tbodyRowClass: "border cursor-pointer",
  tbodyRowExpandableClass: "cursor-pointer",
  tbodyDataClass: "whitespace-nowrap border-gray-300 border-b",
  expandArrowIconClass: "ml-6 flex"
};
var sortByValidValues = new Map([["name", null], ["checkStatuses", null], ["uptime", null], ["latency", null]]);

function CanaryTable(_ref) {
  var checks = _ref.checks,
      labels = _ref.labels,
      history = _ref.history,
      onCheckClick = _ref.onCheckClick,
      showNamespaceTags = _ref.showNamespaceTags,
      hideNamespacePrefix = _ref.hideNamespacePrefix,
      _ref$groupSingleItems = _ref.groupSingleItems,
      groupSingleItems = _ref$groupSingleItems === void 0 ? true : _ref$groupSingleItems,
      _ref$theadStyle = _ref.theadStyle,
      theadStyle = _ref$theadStyle === void 0 ? {} : _ref$theadStyle,
      rest = _objectWithoutProperties(_ref, _excluded);

  var searchParams = window.location.search;

  var _decodeUrlSearchParam = (0, _url.decodeUrlSearchParams)(searchParams),
      groupBy = _decodeUrlSearchParam.groupBy,
      pivotBy = _decodeUrlSearchParam.pivotBy,
      pivotCellType = _decodeUrlSearchParam.pivotCellType,
      pivotLookup = _decodeUrlSearchParam.pivotLabel;

  var _useState = (0, _react.useState)(checks),
      _useState2 = _slicedToArray(_useState, 2),
      tableData = _useState2[0],
      setTableData = _useState2[1]; // update table data if searchParam or check data changes


  (0, _react.useEffect)(function () {
    setTableData(groupBy !== "no-group" ? Object.values((0, _aggregate.getAggregatedGroupedChecks)((0, _grouping.getGroupedChecks)(checks, groupBy), groupSingleItems)) : checks);
  }, [searchParams, checks, groupBy, groupSingleItems]);

  var _useMemo = (0, _react.useMemo)(function () {
    return (0, _lib.prepareRows)({
      tableData: tableData,
      hideNamespacePrefix: hideNamespacePrefix,
      pivotBy: pivotBy,
      pivotLookup: pivotLookup
    });
  }, [hideNamespacePrefix, tableData, pivotBy, pivotLookup]),
      rows = _useMemo.rows,
      meta = _useMemo.meta;

  var isNewPivotSet = (0, _useCheckSetEqualityForPreviousVsCurrent.useCheckSetEqualityForPreviousVsCurrent)(meta.pivotSet);
  var shouldPivot = pivotCellType != null && pivotCellType !== "" && pivotBy != null && pivotBy !== "none";
  var columns = (0, _react.useMemo)(function () {
    if (shouldPivot) {
      return (0, _Columns.makeColumnsForPivot)({
        pivotSet: meta.pivotSet,
        pivotCellType: pivotCellType,
        firstColumns: _columns.firstColumns
      });
    }

    return (0, _Columns.getColumns)({
      columnObject: _columns.columnObject,
      pivotCellType: null
    }); // isNewPivotSet checks the old pivotSet against the new on, so it's a much better test
    // than 'meta.pivotSet', which will probably be referentially new on every fetch of data.
    // Testing the set directly meant we won't have to rebuild the columns, which is predicted to
    // be an expensive operation.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [pivotCellType, isNewPivotSet, pivotBy, pivotLookup]);
  return /*#__PURE__*/(0, _jsxRuntime.jsx)(Table, _objectSpread({
    data: rows,
    columns: columns,
    labels: labels,
    history: history,
    pivotCellType: shouldPivot ? pivotCellType : null,
    onUnexpandableRowClick: onCheckClick,
    hasGrouping: groupBy !== "no-group",
    showNamespaceTags: showNamespaceTags,
    hideNamespacePrefix: hideNamespacePrefix,
    theadStyle: theadStyle
  }, rest));
}

function Table(_ref2) {
  var data = _ref2.data,
      columns = _ref2.columns,
      labels = _ref2.labels,
      history = _ref2.history,
      pivotCellType = _ref2.pivotCellType,
      _ref2$hasGrouping = _ref2.hasGrouping,
      hasGrouping = _ref2$hasGrouping === void 0 ? false : _ref2$hasGrouping,
      onUnexpandableRowClick = _ref2.onUnexpandableRowClick,
      _ref2$showNamespaceTa = _ref2.showNamespaceTags,
      showNamespaceTags = _ref2$showNamespaceTa === void 0 ? false : _ref2$showNamespaceTa,
      _ref2$hideNamespacePr = _ref2.hideNamespacePrefix,
      hideNamespacePrefix = _ref2$hideNamespacePr === void 0 ? false : _ref2$hideNamespacePr,
      _ref2$theadStyle = _ref2.theadStyle,
      theadStyle = _ref2$theadStyle === void 0 ? {} : _ref2$theadStyle,
      rest = _objectWithoutProperties(_ref2, _excluded2);

  var rowFinder = function rowFinder(row) {
    var _row$row$valueLookup;

    var rowValues = (row === null || row === void 0 ? void 0 : row.pivoted) === true ? (_row$row$valueLookup = row[row.valueLookup]) !== null && _row$row$valueLookup !== void 0 ? _row$row$valueLookup : null : row;
    return (rowValues === null || rowValues === void 0 ? void 0 : rowValues.subRows) || [];
  };

  var _useTable = (0, _reactTable.useTable)({
    columns: columns,
    data: data,
    disableMultiSort: true,
    autoResetSortBy: false,
    autoResetExpanded: false,
    getSubRows: rowFinder,
    useControlledState: function useControlledState(state) {
      return (0, _react.useMemo)(function () {
        return _objectSpread(_objectSpread({}, state), {}, {
          pivotCellType: pivotCellType
        });
      }, // eslint-disable-next-line react-hooks/exhaustive-deps
      [state, pivotCellType]);
    }
  }, _reactTable.useSortBy, _reactTable.useExpanded),
      tableState = _useTable.state,
      getTableProps = _useTable.getTableProps,
      getTableBodyProps = _useTable.getTableBodyProps,
      headerGroups = _useTable.headerGroups,
      rows = _useTable.rows,
      setSortBy = _useTable.setSortBy,
      prepareRow = _useTable.prepareRow,
      toggleHideColumn = _useTable.toggleHideColumn,
      toggleRowExpanded = _useTable.toggleRowExpanded;

  var tableSortState = tableState === null || tableState === void 0 ? void 0 : tableState.sortBy; // Hide expander column if there is no grouping

  (0, _react.useEffect)(function () {
    toggleHideColumn("expander", !hasGrouping);
  }, [hasGrouping, toggleHideColumn]); // Set table's sort state according to url params on page load or url change

  (0, _react.useEffect)(function () {
    var searchParams = window.location.search;
    var decodedParams = (0, _url.decodeUrlSearchParams)(searchParams);
    var sortBy = decodedParams.sortBy,
        sortDesc = decodedParams.sortDesc; // check for validity, else reset to default values

    var sortByChecked = sortByValidValues.has(sortBy) ? sortBy : "name";
    var sortDescChecked = typeof sortDesc === "boolean" ? sortDesc : false;
    setSortBy([{
      id: sortByChecked,
      desc: sortDescChecked
    }]);
  }, [setSortBy]); // Table-state changes will trigger url changes

  (0, _react.useEffect)(function () {
    var updateURLBySortState = function updateURLBySortState(sortBy, sortDesc) {
      var searchParams = window.location.search;
      var decodedParams = (0, _url.decodeUrlSearchParams)(searchParams); // check for validity, else reset to default values

      var sortByChecked = sortByValidValues.has(sortBy) ? sortBy : "name";
      var sortDescChecked = typeof sortDesc === "boolean" ? sortDesc : false;

      var newFormState = _objectSpread(_objectSpread({}, decodedParams), {}, {
        sortBy: sortByChecked,
        sortDesc: sortDescChecked
      });

      var encoded = (0, _url.encodeObjectToUrlSearchParams)(newFormState);

      if (window.location.search !== "?".concat(encoded)) {
        history.push("".concat(window.location.pathname, "?").concat(encoded));
      }
    };

    if (tableSortState.length > 0) {
      updateURLBySortState(tableSortState[0].id, tableSortState[0].desc);
    }
  }, [tableSortState, history]);
  return /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", _objectSpread(_objectSpread({
    className: styles.outerDivClass
  }, rest), {}, {
    children: [/*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
      className: styles.topBgClass
    }), /*#__PURE__*/(0, _jsxRuntime.jsxs)("table", _objectSpread(_objectSpread({
      className: styles.tableClass,
      style: {
        borderSpacing: "0"
      }
    }, getTableProps()), {}, {
      children: [/*#__PURE__*/(0, _jsxRuntime.jsx)("thead", {
        className: styles.theadClass,
        style: theadStyle,
        children: headerGroups.map(function (headerGroup) {
          return /*#__PURE__*/(0, _jsxRuntime.jsx)("tr", _objectSpread(_objectSpread({
            className: styles.theadRowClass
          }, headerGroup.getHeaderGroupProps()), {}, {
            children: headerGroup.headers.map(function (column) {
              return /*#__PURE__*/(0, _jsxRuntime.jsx)("th", _objectSpread(_objectSpread({
                className: styles.theadHeaderClass
              }, column.getHeaderProps(column.getSortByToggleProps())), {}, {
                // Table header onClick sorting override:
                // sortDesc cannot be null, only either true/false
                onClick: function onClick() {
                  return column.toggleSortBy(column.isSortedDesc != null ? !column.isSortedDesc : false);
                },
                children: /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
                  className: "flex select-none",
                  children: [column.render("Header"), /*#__PURE__*/(0, _jsxRuntime.jsx)("span", {
                    children: column.isSorted ? column.isSortedDesc ? /*#__PURE__*/(0, _jsxRuntime.jsx)(_ti.TiArrowSortedUp, {}) : /*#__PURE__*/(0, _jsxRuntime.jsx)(_ti.TiArrowSortedDown, {}) : ""
                  })]
                })
              }), column.Header);
            })
          }), headerGroup.getHeaderGroupProps().key);
        })
      }), /*#__PURE__*/(0, _jsxRuntime.jsx)("tbody", _objectSpread(_objectSpread({
        className: styles.tbodyClass
      }, getTableBodyProps()), {}, {
        children: rows.length > 0 && rows.map(function (row) {
          prepareRow(row);
          row.showNamespaceTags = showNamespaceTags;
          row.hideNamespacePrefix = hideNamespacePrefix;
          return /*#__PURE__*/(0, _jsxRuntime.jsx)("tr", _objectSpread(_objectSpread({
            className: "".concat(styles.tbodyRowClass, " ").concat(row.canExpand ? styles.tbodyRowExpandableClass : ""),
            style: {},
            onClick: row.canExpand ? function () {
              return toggleRowExpanded(row.id);
            } : function () {
              return onUnexpandableRowClick(row.original);
            }
          }, row.getRowProps()), {}, {
            children: row.cells.map(function (cell) {
              return /*#__PURE__*/(0, _jsxRuntime.jsx)("td", _objectSpread(_objectSpread({
                className: "".concat(styles.tbodyDataClass, " ").concat(cell.column.cellClass || "")
              }, cell.getCellProps()), {}, {
                children: cell.render("Cell")
              }), cell.column.Header);
            })
          }), row.id);
        })
      }))]
    })), rows.length <= 0 && /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
      className: "flex items-center justify-center py-20 px-2  border-b border-gray-300 text-center text-gray-400",
      children: "No data available"
    })]
  }));
}