"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.ConfigEvidenceView = ConfigEvidenceView;
exports.EvidenceAccordion = EvidenceAccordion;
exports.EvidenceItem = EvidenceItem;
exports.EvidenceSection = EvidenceSection;
exports.createHunks = createHunks;

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

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

var _outline = require("@heroicons/react/outline");

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

var _logsTable = require("../Logs/Table/logs-table");

var _Topology = require("../Topology");

var _Icon = require("../Icon");

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

var _excluded = ["title", "date", "children"],
    _excluded2 = ["evidenceList", "hypothesis", "titlePrepend", "onButtonClick", "isLoading"];

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

function EvidenceItem(_ref) {
  var evidence = _ref.evidence;

  if (evidence.type === "log") {
    return /*#__PURE__*/(0, _jsxRuntime.jsx)(_logsTable.LogsTable, {
      logs: evidence.evidence,
      title: ""
    });
  }

  if (evidence.type === "topology") {
    return /*#__PURE__*/(0, _jsxRuntime.jsx)(_Topology.TopologyCard, {
      topologyId: evidence.evidence.id,
      size: "small"
    });
  }

  if (evidence.type === "config") {
    return /*#__PURE__*/(0, _jsxRuntime.jsx)(EvidenceAccordion, {
      date: evidence.created_at,
      title: evidence.description,
      children: /*#__PURE__*/(0, _jsxRuntime.jsx)(ConfigEvidenceView, {
        evidenceItem: evidence
      })
    });
  }

  return null;
}

function EvidenceAccordion(_ref2) {
  var title = _ref2.title,
      date = _ref2.date,
      children = _ref2.children,
      rest = _objectWithoutProperties(_ref2, _excluded);

  var _useState = (0, _react.useState)(false),
      _useState2 = _slicedToArray(_useState, 2),
      expanded = _useState2[0],
      setExpanded = _useState2[1];

  return /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", _objectSpread(_objectSpread({
    className: "border-b last:border-b-0 flex flex-col"
  }, rest), {}, {
    children: [/*#__PURE__*/(0, _jsxRuntime.jsxs)("button", {
      className: "".concat(expanded && "border-b", " py-2 px-2 flex flex-row items-center"),
      onClick: function onClick() {
        return setExpanded(!expanded);
      },
      type: "button",
      children: [/*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
        className: "mr-2",
        children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_outline.ChevronRightIcon, {
          className: "h-5 w-5 transform ".concat(expanded && "rotate-90")
        })
      }), /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
        className: "flex justify-between w-full items-center",
        children: [title || /*#__PURE__*/(0, _jsxRuntime.jsx)("span", {
          className: "text-gray-400",
          children: "(no title)"
        }), date && /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
          className: "text-gray-400 text-sm",
          children: (0, _dayjs.default)(date).format("HH:mm A, MMM DD, YYYY")
        })]
      })]
    }), expanded && children]
  }));
}

function ConfigEvidenceView(_ref3) {
  var _evidenceItem$evidenc, _evidenceItem$evidenc2;

  var evidenceItem = _ref3.evidenceItem;
  var hunkLineGap = 3;
  var fullConfig = (evidenceItem === null || evidenceItem === void 0 ? void 0 : (_evidenceItem$evidenc = evidenceItem.evidence) === null || _evidenceItem$evidenc === void 0 ? void 0 : _evidenceItem$evidenc.config_full) || {};
  var selectedLines = Object.keys(evidenceItem === null || evidenceItem === void 0 ? void 0 : (_evidenceItem$evidenc2 = evidenceItem.evidence) === null || _evidenceItem$evidenc2 === void 0 ? void 0 : _evidenceItem$evidenc2.lines) || [];

  var _useState3 = (0, _react.useState)([]),
      _useState4 = _slicedToArray(_useState3, 2),
      hunks = _useState4[0],
      setHunks = _useState4[1];

  (0, _react.useEffect)(function () {
    var _evidenceItem$evidenc3, _evidenceItem$evidenc4;

    setHunks(createHunks(evidenceItem === null || evidenceItem === void 0 ? void 0 : (_evidenceItem$evidenc3 = evidenceItem.evidence) === null || _evidenceItem$evidenc3 === void 0 ? void 0 : _evidenceItem$evidenc3.config_full, evidenceItem === null || evidenceItem === void 0 ? void 0 : (_evidenceItem$evidenc4 = evidenceItem.evidence) === null || _evidenceItem$evidenc4 === void 0 ? void 0 : _evidenceItem$evidenc4.lines, hunkLineGap));
  }, [evidenceItem]);
  return /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
    className: "",
    children: evidenceItem ? /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
      className: "flex flex-col p-1",
      children: hunks.map(function (_ref4, hunkIndex) {
        var _ref5 = _slicedToArray(_ref4, 2),
            hunkStart = _ref5[0],
            hunkEnd = _ref5[1];

        return /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
          children: [/*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
            className: "border mb-1 last:mb-0",
            children: Object.entries(fullConfig).filter(function (_ref6) {
              var _ref7 = _slicedToArray(_ref6, 1),
                  lineIndex = _ref7[0];

              return lineIndex >= hunkStart && lineIndex <= hunkEnd;
            }).map(function (_ref8) {
              var _ref9 = _slicedToArray(_ref8, 2),
                  lineIndex = _ref9[0],
                  line = _ref9[1];

              var selected = selectedLines.includes(lineIndex);
              return /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
                className: "flex",
                style: {
                  background: selected && "#cfe3ff"
                },
                children: [/*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
                  className: "text-xs flex items-center justify-end px-1 text-gray-600 border-r w-8 select-none",
                  children: lineIndex
                }), /*#__PURE__*/(0, _jsxRuntime.jsx)("code", {
                  className: "px-2 whitespace-pre-wrap text-xs ".concat(selected ? "text-gray-800" : "text-gray-600"),
                  children: line
                })]
              }, lineIndex);
            })
          }), hunkIndex < hunks.length - 1 && /*#__PURE__*/(0, _jsxRuntime.jsx)(_outline.DotsVerticalIcon, {
            className: "h-4 w-4 text-gray-400 mb-1 ml-2"
          })]
        }, "".concat(hunkStart, "-").concat(hunkEnd));
      })
    }) : /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
      children: "No Evidence"
    })
  });
}

function createHunks(fullConfig, selectedLines, hunkLineGap) {
  var hunks = [];
  var lineNumbers = Object.keys(selectedLines);
  var hunkStart = Math.max(0, parseInt(lineNumbers[0], 10) - hunkLineGap);
  var prevNum = parseInt(lineNumbers[0], 10);
  lineNumbers.forEach(function (curr, idx) {
    var currentNum = parseInt(curr, 10);

    if (currentNum - prevNum > hunkLineGap) {
      // went past hunk gap threshold; break gap.
      hunks.push([hunkStart, prevNum + hunkLineGap]);
      hunkStart = currentNum - hunkLineGap;
    }

    if (idx === lineNumbers.length - 1) {
      // last hunk, make sure to push.
      hunks.push([hunkStart, currentNum + hunkLineGap > Object.keys(fullConfig).length - 1 ? Object.keys(fullConfig).length - 1 : currentNum + hunkLineGap]);
    }

    prevNum = currentNum;
  });
  return hunks;
}

function EvidenceSection(_ref10) {
  var evidenceList = _ref10.evidenceList,
      hypothesis = _ref10.hypothesis,
      titlePrepend = _ref10.titlePrepend,
      onButtonClick = _ref10.onButtonClick,
      isLoading = _ref10.isLoading,
      rest = _objectWithoutProperties(_ref10, _excluded2);

  return /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", _objectSpread(_objectSpread({
    className: rest.className
  }, rest), {}, {
    children: [/*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
      className: "flex justify-between items-center",
      children: [/*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
        className: "flex align-baseline font-inter text-large font-semibold",
        children: [/*#__PURE__*/(0, _jsxRuntime.jsx)("h2", {
          className: "text-gray-900 mr-2",
          children: titlePrepend
        }), /*#__PURE__*/(0, _jsxRuntime.jsx)("button", {
          type: "button",
          className: "btn-round btn-round-primary btn-round-sm",
          children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_all.BsPlusLg, {})
        })]
      }), /*#__PURE__*/(0, _jsxRuntime.jsx)("button", {
        type: "button",
        onClick: onButtonClick,
        className: "hidden inline-flex items-center px-2.5 py-1.5 mb-1 border border-transparent text-xs font-medium rounded text-indigo-700 bg-indigo-100 disabled:bg-gray-200 disabled:text-gray-400 hover:bg-indigo-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500",
        children: "Add evidence"
      })]
    }), /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
      className: "mt-2.5",
      children: !isLoading ? evidenceList && evidenceList.length > 0 ? /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
        className: "border rounded-md",
        children: evidenceList.map(function (evidence) {
          return /*#__PURE__*/(0, _jsxRuntime.jsx)(EvidenceItem, {
            evidence: evidence
          }, evidence.id);
        })
      }) : /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
        className: "border border-dashed border-gray-300 rounded-8px flex justify-center pt-8 mt-2.5",
        children: /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
          className: "flex flex-col mx-auto mb-6",
          children: [/*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
            className: "mx-auto",
            children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_Icon.Icon, {
              name: "database-plus",
              className: "w-10 h-10"
            })
          }), /*#__PURE__*/(0, _jsxRuntime.jsx)("p", {
            className: "text-sm leading-5 font-medium pt-2.5",
            children: "Add evidence"
          })]
        })
      }) : /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
        className: "text-sm text-gray-400",
        children: "Loading..."
      })
    })]
  }));
}