"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.IncidentDetailsPage = IncidentDetailsPage;

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

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

var _lodash = require("lodash");

var _hypothesis = require("../../api/services/hypothesis");

var _incident = require("../../api/services/incident");

var _HypothesisBuilder = require("../../components/HypothesisBuilder");

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

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

var _Change = require("../../components/Change");

var _topologyCard = require("../../components/Topology/topology-card");

var _useIncidentQuery = require("../../components/query-hooks/useIncidentQuery");

var _useUpdateHypothesisMutation = require("../../components/mutations/useUpdateHypothesisMutation");

var _useCreateHypothesisMutation = require("../../components/mutations/useCreateHypothesisMutation");

var _IncidentDetails = require("../../components/IncidentDetails");

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

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 mapNode(node) {
  return _objectSpread(_objectSpread({}, node), {}, {
    evidence: node.evidence || [],
    links: node.links || [],
    comments: node.comments || [],
    children: node.children || []
  });
}

var NULL_NODE = mapNode({
  title: "Empty",
  id: "empty_tree",
  children: []
}); // temporary tree-building method that is incorrect.

function buildTreeFromHypothesisList(list) {
  var tree = {};

  if (list.length === 0) {
    return NULL_NODE;
  }

  list.forEach(function (node) {
    tree[node.id] = mapNode(node);
  }); // 2nd pass to add children

  list.forEach(function (node) {
    if (node.parent_id != null) {
      tree[node.parent_id].children.push(tree[node.id]);
    }
  }); // 3rd pass to remove children from root

  list.forEach(function (node) {
    if (node.parent_id != null) {
      delete tree[node.id];
    }
  });
  return (0, _lodash.values)(tree)[0];
}

function IncidentDetailsPage() {
  var _useParams = (0, _reactRouterDom.useParams)(),
      incidentId = _useParams.id;

  var isNewlyCreated = false; // TODO: set this to true if its a newly created incident

  var incidentQuery = (0, _useIncidentQuery.useIncidentQuery)(incidentId);
  var isLoading = incidentQuery.isLoading;
  var incidentData = (0, _react.useMemo)(function () {
    return incidentQuery.data;
  }, [incidentQuery.data]);
  var error = incidentData == null || !(incidentData !== null && incidentData !== void 0 && incidentData.length);
  var incident = (0, _react.useMemo)(function () {
    return incidentData !== null && incidentData !== void 0 && incidentData.length ? incidentData[0] : null;
  }, [incidentData]);
  var status = (0, _react.useMemo)(function () {
    var _incident$status;

    return (_incident$status = incident === null || incident === void 0 ? void 0 : incident.status) !== null && _incident$status !== void 0 ? _incident$status : null;
  }, [incident]);
  var loadedTree = (0, _react.useMemo)(function () {
    return incident ? buildTreeFromHypothesisList(incident.hypothesis) : null;
  }, [incident]);
  var updateMutation = (0, _useUpdateHypothesisMutation.useUpdateHypothesisMutation)({
    incidentId: incidentId
  });
  var createMutation = (0, _useCreateHypothesisMutation.useCreateHypothesisMutation)({
    incidentId: incidentId
  });

  var updateStatus = function updateStatus(status) {
    return (0, _incident.updateIncident)(incident.id, {
      status: status
    }).then(function () {
      return incidentQuery.refetch();
    });
  };

  var updateIncidentHandler = (0, _react.useCallback)(function (newDataIncident) {
    (0, _incident.updateIncident)(incident.id, newDataIncident).then(function () {
      return incidentQuery.refetch();
    });
  }, [incidentQuery, incident]);

  if (incident == null) {
    return /*#__PURE__*/(0, _jsxRuntime.jsx)(_Loading.Loading, {});
  }

  return /*#__PURE__*/(0, _jsxRuntime.jsx)(_Layout.SearchLayout, {
    onRefresh: function onRefresh() {
      return incidentQuery.refetch();
    },
    title: /*#__PURE__*/(0, _jsxRuntime.jsx)(_jsxRuntime.Fragment, {
      children: /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
        className: "flex my-auto",
        children: /*#__PURE__*/(0, _jsxRuntime.jsxs)("span", {
          className: "text-xl flex",
          children: [" ", /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactRouterDom.Link, {
            to: "/incidents",
            children: "Incidents\xA0"
          }), " / ", !isLoading && /*#__PURE__*/(0, _jsxRuntime.jsx)(_jsxRuntime.Fragment, {
            children: /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
              className: "font-semibold",
              children: /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
                children: ["\xA0", incident.title]
              })
            })
          })]
        })
      })
    }),
    children: /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
      className: "mt-2 max-w-3xl mx-auto grid grid-cols-1 gap-6 sm:px-6 lg:max-w-7xl lg:grid-flow-col-dense lg:grid-cols-3",
      children: [/*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
        className: "space-y-6 lg:col-start-1 lg:col-span-2",
        children: [/*#__PURE__*/(0, _jsxRuntime.jsx)("section", {
          "aria-labelledby": "notes-title",
          children: /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
            className: "bg-white sm:overflow-hidden",
            children: /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
              className: "px-2 py-2 flex flex-nowrap",
              children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_topologyCard.TopologyCard, {
                size: "medium",
                topologyId: "017ed3af-c25a-5362-175d-40e7864ed7b7",
                depth: 2
              })
            })
          })
        }), /*#__PURE__*/(0, _jsxRuntime.jsx)("section", {
          "aria-labelledby": "notes-title",
          children: /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
            className: "bg-white shadow sm:rounded-lg sm:overflow-hidden",
            children: /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
              className: "px-2 py-2",
              children: !isLoading ? /*#__PURE__*/(0, _jsxRuntime.jsx)(_HypothesisBuilder.HypothesisBuilder, {
                loadedTree: loadedTree // showGeneratedOutput
                ,
                initialEditMode: isNewlyCreated,
                api: {
                  incidentId: incidentId,
                  create: _hypothesis.createHypothesis,
                  delete: _hypothesis.deleteHypothesis,
                  deleteBulk: _hypothesis.deleteHypothesisBulk,
                  update: _hypothesis.updateHypothesis,
                  updateMutation: updateMutation,
                  createMutation: createMutation
                }
              }) : /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
                children: !error && "fetching tree..."
              })
            })
          })
        })]
      }), /*#__PURE__*/(0, _jsxRuntime.jsxs)("section", {
        "aria-labelledby": "timeline-title",
        className: "lg:col-start-3 lg:col-span-1",
        children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_IncidentDetails.IncidentDetails, {
          incident: incident,
          updateStatusHandler: function updateStatusHandler() {
            return updateStatus(status === "open" ? "closed" : "open");
          },
          updateIncidentHandler: updateIncidentHandler,
          textButton: status === "open" ? "Close" : "Reopen"
        }), /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
          className: "bg-white px-4 py-5 mt-4  shadow sm:rounded-lg sm:px-6",
          children: /*#__PURE__*/(0, _jsxRuntime.jsx)("section", {
            "aria-labelledby": "applicant-information-title",
            children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_Change.Changelog, {})
          })
        })]
      })]
    })
  });
}