"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.LogsTable = void 0;

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

var _ansiToHtml = _interopRequireDefault(require("ansi-to-html"));

var _dompurify = _interopRequireDefault(require("dompurify"));

var _lodash = require("lodash");

var _dayjs = _interopRequireDefault(require("dayjs"));

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

var _clsx = _interopRequireDefault(require("clsx"));

var _propTypes = _interopRequireDefault(require("prop-types"));

var _all = require("react-icons/all");

var _IndeterminateCheckbox = require("../../IndeterminateCheckbox/IndeterminateCheckbox");

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

var _excluded = ["key"];

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

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

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

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

var convert = new _ansiToHtml.default();

var LogsTable = function LogsTable(_ref) {
  var logs = _ref.logs,
      actions = _ref.actions,
      variant = _ref.variant;

  if (logs != null && !(0, _lodash.isArray)(logs)) {
    try {
      logs = JSON.parse(logs);
    } catch (e) {
      // eslint-disable-next-line no-console
      console.error("cannot parse logs", logs);
      logs = [];
    }
  }

  if (logs == null) {
    logs = [];
  }

  var columns = (0, _react.useMemo)(function () {
    return [{
      id: "selection",
      Header: "Time",
      accessor: "timestamp",
      Cell: function timestampCell(_ref2) {
        var row = _ref2.cell.row;
        return /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
          className: "min-w-max flex flex-row items-center",
          children: [variant === "comfortable" ? /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
            className: "mr-1.5",
            children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_IndeterminateCheckbox.IndeterminateCheckbox, _objectSpread({}, row.getToggleRowSelectedProps()))
          }) : /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
            className: "mr-2.5",
            children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_all.BsFillBarChartFill, {
              className: "text-dark-blue text-base"
            })
          }), /*#__PURE__*/(0, _jsxRuntime.jsx)("p", {
            children: (0, _dayjs.default)(row.original.timestamp).format("MMM DD, YYYY HH:mm.ss.SSS")
          })]
        });
      }
    }, {
      Header: function MessageHeader(props) {
        var state = props.state,
            selectedFlatRows = props.selectedFlatRows;
        var selectedRowIds = state.selectedRowIds;
        return /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
          className: "flex justify-between",
          children: [/*#__PURE__*/(0, _jsxRuntime.jsx)("span", {
            className: "align-middle my-auto",
            children: "Message"
          }), /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
            className: "flex justify-end -m-2 flex-wrap",
            children: actions.map(function (action) {
              return /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
                className: "p-2",
                children: /*#__PURE__*/(0, _jsxRuntime.jsx)("button", {
                  type: "button",
                  disabled: !Object.keys(selectedRowIds).length,
                  onClick: function onClick() {
                    action.handler(selectedFlatRows.map(function (d) {
                      return d.original;
                    }));
                  },
                  className: (0, _clsx.default)(Object.keys(selectedRowIds).length === 0 ? "btn-disabled" : "btn-primary"),
                  children: action.label
                })
              }, action.label);
            })
          })]
        });
      },
      accessor: "message",
      id: "message",
      Cell: function messageCell(_ref3) {
        var value = _ref3.cell.value;
        return /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
          className: "break-all" // eslint-disable-next-line react/no-danger
          ,
          dangerouslySetInnerHTML: {
            __html: _dompurify.default.sanitize(convert.toHtml(value || ""))
          }
        });
      }
    }];
  }, [actions, variant]);
  var data = (0, _react.useMemo)(function () {
    return logs;
  }, [logs]);

  var _useTable = (0, _reactTable.useTable)({
    columns: columns,
    data: data
  }, _reactTable.useRowSelect, function (hooks) {
    hooks.visibleColumns.push(function (columns) {
      return _toConsumableArray(columns);
    });
  }),
      getTableProps = _useTable.getTableProps,
      getTableBodyProps = _useTable.getTableBodyProps,
      headerGroups = _useTable.headerGroups,
      rows = _useTable.rows,
      prepareRow = _useTable.prepareRow;

  return /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
    className: "pb-12",
    children: /*#__PURE__*/(0, _jsxRuntime.jsxs)("table", _objectSpread(_objectSpread({
      className: (0, _clsx.default)("w-full", variant === "comfortable" ? "comfortable-table" : "compact-table")
    }, getTableProps()), {}, {
      children: [/*#__PURE__*/(0, _jsxRuntime.jsx)("thead", {
        children: headerGroups.map(function (headerGroup) {
          var _headerGroup$getHeade = headerGroup.getHeaderGroupProps(),
              key = _headerGroup$getHeade.key,
              restHeaderGroupProps = _objectWithoutProperties(_headerGroup$getHeade, _excluded);

          return /*#__PURE__*/(0, _jsxRuntime.jsx)("tr", _objectSpread(_objectSpread({}, restHeaderGroupProps), {}, {
            children: headerGroup.headers.map(function (column) {
              return /*#__PURE__*/(0, _jsxRuntime.jsx)("th", _objectSpread(_objectSpread({}, column.getHeaderProps()), {}, {
                children: column.render("Header")
              }), column.id);
            })
          }), key);
        })
      }), /*#__PURE__*/(0, _jsxRuntime.jsx)("tbody", _objectSpread(_objectSpread({}, getTableBodyProps()), {}, {
        children: rows.map(function (row) {
          prepareRow(row);
          return /*#__PURE__*/(0, _jsxRuntime.jsx)("tr", _objectSpread(_objectSpread({}, row.getRowProps()), {}, {
            children: row.cells.map(function (cell) {
              return /*#__PURE__*/(0, _jsxRuntime.jsx)("td", _objectSpread(_objectSpread({}, cell.getCellProps()), {}, {
                children: cell.render("Cell")
              }), cell.row.id);
            })
          }), row.id);
        })
      }))]
    }))
  });
};

exports.LogsTable = LogsTable;
LogsTable.propTypes = {
  logs: _propTypes.default.arrayOf(_propTypes.default.shape({})).isRequired,
  actions: _propTypes.default.arrayOf(_propTypes.default.shape({})),
  variant: _propTypes.default.oneOf(["comfortable", "compact"])
};
LogsTable.defaultProps = {
  actions: [],
  variant: "comfortable"
};