"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 _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 _JSONViewer = require("../../components/JSONViewer");

var _BreadcrumbNav = require("../../components/BreadcrumbNav");

var _Button = require("../../components/Button");

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 _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 _useSearchParams = (0, _reactRouterDom.useSearchParams)(),
      _useSearchParams2 = _slicedToArray(_useSearchParams, 2),
      params = _useSearchParams2[0],
      setParams = _useSearchParams2[1];

  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 _useOutletContext = (0, _reactRouterDom.useOutletContext)(),
      setTitle = _useOutletContext.setTitle,
      setTabRight = _useOutletContext.setTabRight;

  (0, _react.useEffect)(function () {
    (0, _configs.getConfig)(id).then(function (res) {
      var data = res === null || res === void 0 ? void 0 : res.data[0];
      setConfigDetails(data);
      setTitle( /*#__PURE__*/(0, _jsxRuntime.jsx)(_BreadcrumbNav.BreadcrumbNav, {
        list: [{
          to: "/config",
          title: "Config"
        }, /*#__PURE__*/(0, _jsxRuntime.jsx)("b", {
          children: data === null || data === void 0 ? void 0 : data.name
        }, "title")]
      }));
    }).catch(function (err) {
      return (0, _toast.toastError)(err);
    }).finally(function () {
      setIsLoading(false);
    }); // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [id]);
  (0, _react.useEffect)(function () {
    if (!(configDetails !== null && configDetails !== void 0 && configDetails.config)) {
      return;
    }

    var selected = params.getAll("selected");
    setChecked(Object.fromEntries(selected.map(function (x) {
      return [x, true];
    })));
  }, [params, configDetails]);
  (0, _react.useEffect)(function () {
    var selected = Object.keys(checked);
    setParams({
      selected: selected
    });
  }, [checked]);
  var handleClick = (0, _react.useCallback)(function (idx) {
    setChecked(function (checked) {
      var obj = _objectSpread({}, checked);

      if (obj[idx]) {
        delete obj[idx];
      } else {
        obj[idx] = true;
      }

      return obj;
    });
  }, []);

  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.");
    }
  };

  var code = (0, _react.useMemo)(function () {
    return (configDetails === null || configDetails === void 0 ? void 0 : configDetails.config) && JSON.stringify(configDetails.config, null, 2);
  }, [configDetails]); // TODO(ciju): make this lazy. Only needed for IncidentCreate.

  var configLines = (0, _react.useMemo)(function () {
    return code && code.split("\n");
  }, [code]);
  var selectedCount = Object.keys(checked).length;
  var selectionControls = selectedCount > 0 ? /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
    className: "flex flex-row space-x-2",
    children: [/*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
      className: "flex items-center mx-4",
      children: [selectedCount, " lines selected"]
    }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_Button.Button, {
      className: "btn-secondary",
      text: "Clear",
      onClick: function onClick() {
        setChecked({});
        return Promise.resolve();
      }
    }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_Button.Button, {
      text: "Share",
      onClick: function onClick() {
        handleShare();
        return Promise.resolve();
      }
    }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_Button.Button, {
      text: "Create Incident",
      onClick: function onClick() {
        setShowIncidentModal(true);
        return Promise.resolve();
      }
    })]
  }) : null;
  (0, _react.useEffect)(function () {
    setTabRight(selectionControls);
    return function () {
      return setTabRight(null);
    };
  }, [checked]);
  return /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
    className: "flex flex-col items-start",
    children: [/*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
      className: "flex flex-col w-full border rounded-md rounded-tl-none",
      children: !isLoading ? /*#__PURE__*/(0, _jsxRuntime.jsx)(_JSONViewer.JSONViewer, {
        code: code,
        showLineNo: true,
        onClick: handleClick,
        selections: checked
      }) : /*#__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: configLines,
          type: "config",
          lines: Object.fromEntries(Object.keys(checked).map(function (n) {
            return [n, configLines[n]];
          }))
        }
      })
    })]
  });
}