"use strict";

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

var _react = require("react");

var _reactHotToast = _interopRequireDefault(require("react-hot-toast"));

var _reactRouterDom = require("react-router-dom");

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

var _Layout = require("../../components/Layout");

var _toast = require("../../components/Toast/toast");

var _Modal = require("../../components/Modal");

var _IncidentCreate = require("../../components/Incidents/IncidentCreate");

var _configs = require("../../api/services/configs");

var _Loading = require("../../components/Loading");

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); if (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 = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { 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 ConfigDetailsPage() {
  var navigate = (0, _reactRouterDom.useNavigate)();

  var _useParams = (0, _reactRouterDom.useParams)(),
      id = _useParams.id;

  var _useState = (0, _react.useState)(true),
      _useState2 = _slicedToArray(_useState, 2),
      isLoading = _useState2[0],
      setIsLoading = _useState2[1];

  var _useState3 = (0, _react.useState)(false),
      _useState4 = _slicedToArray(_useState3, 2),
      showIncidentModal = _useState4[0],
      setShowIncidentModal = _useState4[1];

  var _useState5 = (0, _react.useState)({}),
      _useState6 = _slicedToArray(_useState5, 2),
      checked = _useState6[0],
      setChecked = _useState6[1];

  var _useState7 = (0, _react.useState)(),
      _useState8 = _slicedToArray(_useState7, 2),
      configDetails = _useState8[0],
      setConfigDetails = _useState8[1];

  var _useState9 = (0, _react.useState)([]),
      _useState10 = _slicedToArray(_useState9, 2),
      jsonLines = _useState10[0],
      setJsonLines = _useState10[1];

  (0, _react.useEffect)(function () {
    (0, _configs.getConfig)(id).then(function (res) {
      setConfigDetails(res === null || res === void 0 ? void 0 : res.data[0]);
    }).catch(function (err) {
      return (0, _toast.toastError)(err);
    }).finally(function () {
      setIsLoading(false);
    });
  }, []);
  (0, _react.useEffect)(function () {
    var json = configDetails === null || configDetails === void 0 ? void 0 : configDetails.config;

    if (json) {
      var _jsonLines = json.split("\n");

      setJsonLines(_jsonLines.reduce(function (acc, currLine, idx) {
        acc[idx] = currLine;
        return acc;
      }, {}));

      var _decodeUrlSearchParam = (0, _url.decodeUrlSearchParams)(window.location.search),
          selected = _decodeUrlSearchParam.selected;

      if (selected) {
        var newChecked = selected.reduce(function (acc, lineNum) {
          acc[lineNum] = true;
          return acc;
        }, {});
        setChecked(newChecked);
      }
    }
  }, [configDetails]);

  var handleClick = function handleClick(index) {
    var selected = !checked[index];

    var newChecked = _objectSpread({}, checked);

    newChecked[index] = selected;

    if (!selected) {
      delete newChecked[index];
    }

    setChecked(newChecked);
    (0, _url.updateParams)({
      selected: Object.keys(newChecked).map(function (key) {
        return parseInt(key, 10);
      })
    });
  };

  var handleShare = function handleShare() {
    var href = window.location.href;
    var copyString = "".concat(href);

    if (window.isSecureContext) {
      navigator.clipboard.writeText(copyString).then(function () {
        (0, _reactHotToast.default)("Copied to clipboard");
      });
    } else {
      (0, _toast.toastError)("Unable to copy to clipboard due to lack of HTTPS. Please contact the system administrator about this issue.");
    }
  };

  return /*#__PURE__*/(0, _jsxRuntime.jsx)(_Layout.SearchLayout, {
    title: configDetails !== null && configDetails !== void 0 && configDetails.name ? "Config Details for ".concat(configDetails.name) : "Config Details",
    children: /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
      className: "flex flex-col items-start",
      children: [/*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
        className: "mb-4 flex flex-row iems-center",
        children: [/*#__PURE__*/(0, _jsxRuntime.jsx)("button", {
          className: "border rounded-md px-3 py-1 text-sm",
          type: "button",
          onClick: function onClick() {
            return navigate("/config");
          },
          children: "Back"
        }), Object.keys(checked).length > 0 && /*#__PURE__*/(0, _jsxRuntime.jsxs)(_jsxRuntime.Fragment, {
          children: [/*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
            className: "flex items-center mx-4",
            children: [Object.keys(checked).length, " lines selected"]
          }), /*#__PURE__*/(0, _jsxRuntime.jsx)("button", {
            className: "border rounded-md px-3 py-1 mr-2 text-sm",
            type: "button",
            onClick: function onClick() {
              setChecked({});
              (0, _url.updateParams)({
                selected: null
              });
            },
            children: "Clear"
          }), /*#__PURE__*/(0, _jsxRuntime.jsx)("button", {
            className: "border rounded-md px-3 py-1 mr-2 text-sm",
            type: "button",
            onClick: function onClick() {
              handleShare();
            },
            children: "Share"
          }), /*#__PURE__*/(0, _jsxRuntime.jsx)("button", {
            className: "border rounded-md px-3 py-1 text-sm",
            type: "button",
            onClick: function onClick() {
              return setShowIncidentModal(true);
            },
            children: "Create Incident"
          })]
        })]
      }), /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
        className: "flex flex-col w-full border rounded-md",
        children: !isLoading ? Object.entries(jsonLines).map(function (_ref) {
          var _ref2 = _slicedToArray(_ref, 2),
              lineIndex = _ref2[0],
              line = _ref2[1];

          return /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
            style: {
              background: checked[lineIndex] ? "#cfe3ff" : "",
              borderColor: checked[lineIndex] ? "#cfe3ff" : ""
            },
            className: "flex flex-row",
            children: [/*#__PURE__*/(0, _jsxRuntime.jsxs)("button", {
              type: "button",
              onClick: function onClick() {
                return handleClick(lineIndex);
              },
              className: "flex text-xs mr-2 select-none border-r w-12 justify-between pb-px",
              children: [/*#__PURE__*/(0, _jsxRuntime.jsx)("span", {
                className: "w-4 flex items-center justify-center",
                style: {
                  color: checked[lineIndex] ? "#dd0707" : "#086008"
                },
                children: checked[lineIndex] ? "-" : "+"
              }), /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
                className: "text-xs flex items-center justify-end px-1 text-gray-600",
                style: {
                  borderColor: checked[lineIndex] ? "#cfe3ff" : ""
                },
                children: lineIndex
              })]
            }), /*#__PURE__*/(0, _jsxRuntime.jsx)("code", {
              className: "whitespace-pre-wrap text-xs text-gray-800",
              children: line
            })]
          }, lineIndex);
        }) : /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
          className: "h-32 flex items-center justify-center",
          children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_Loading.Loading, {})
        })
      }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_Modal.Modal, {
        open: showIncidentModal,
        onClose: function onClose() {
          return setShowIncidentModal(false);
        },
        size: "small",
        title: "Create New Incident from Selected Evidence",
        children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_IncidentCreate.IncidentCreate, {
          callback: function callback(response) {
            navigate("/incidents/".concat(response.id), {
              replace: true
            });
          },
          evidence: {
            configId: id,
            configName: configDetails === null || configDetails === void 0 ? void 0 : configDetails.name,
            config: jsonLines,
            type: "config",
            lines: Object.keys(checked).reduce(function (acc, lineNum) {
              acc[lineNum] = jsonLines[lineNum];
              return acc;
            }, {})
          }
        })
      })]
    })
  });
}