"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

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

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

var _reactHookForm = require("react-hook-form");

var _uuid = require("uuid");

var _evidence = require("../../../api/services/evidence");

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

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

var _context = require("../../../context");

var _Dropdown = require("../../Dropdown");

var _TextInput = require("../../TextInput");

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

var _excluded = ["selectedLogs", "callback"];

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

var incidentSelectionsTemplate = {// new: {
  //   id: "dropdown-incident-new",
  //   name: "new",
  //   description: "New Incident",
  //   icon: <BiPlus />,
  //   value: "new"
  // }
};
var evidenceTypeItems = {
  log: {
    id: "dropdown-type-log",
    name: "log",
    description: "Log",
    value: "log"
  }
};

function LogsIncidentLinker(_ref) {
  var _errors$description, _errors$type;

  var selectedLogs = _ref.selectedLogs,
      callback = _ref.callback,
      rest = _objectWithoutProperties(_ref, _excluded);

  var _useForm = (0, _reactHookForm.useForm)({
    defaultValues: {
      incident: "new",
      hypothesis: null,
      type: "log",
      description: ""
    }
  }),
      control = _useForm.control,
      watch = _useForm.watch,
      handleSubmit = _useForm.handleSubmit,
      setValue = _useForm.setValue,
      errors = _useForm.formState.errors;

  var selectedIncident = watch("incident");
  var user = (0, _context.useUser)();

  var _useState = (0, _react.useState)([]),
      _useState2 = _slicedToArray(_useState, 2),
      incidentsList = _useState2[0],
      setIncidentsList = _useState2[1];

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

  var _useState5 = (0, _react.useState)({
    incident: true,
    hypothesis: false,
    submit: false
  }),
      _useState6 = _slicedToArray(_useState5, 2),
      isLoading = _useState6[0],
      setIsLoading = _useState6[1];

  var getIncidentSelections = function getIncidentSelections(list) {
    return _objectSpread(_objectSpread({}, incidentSelectionsTemplate), list.reduce(function (acc, incident) {
      var _incident$title;

      acc[incident.id] = {
        id: "dropdown-incident-".concat(incident.id),
        name: incident.id,
        description: (incident === null || incident === void 0 ? void 0 : (_incident$title = incident.title) === null || _incident$title === void 0 ? void 0 : _incident$title.length) > 0 ? incident.title : "(no title)",
        value: incident.id
      };
      return acc;
    }, {}));
  };

  var getHypothesisSelections = function getHypothesisSelections(list) {
    return list.reduce(function (acc, hypothesis) {
      var _hypothesis$title;

      acc[hypothesis.id] = {
        id: "dropdown-hypothesis-".concat(hypothesis.id),
        name: hypothesis.id,
        description: (hypothesis === null || hypothesis === void 0 ? void 0 : (_hypothesis$title = hypothesis.title) === null || _hypothesis$title === void 0 ? void 0 : _hypothesis$title.length) > 0 ? hypothesis.title : "(no title)",
        value: hypothesis.id
      };
      return acc;
    }, {});
  }; // fetch incidents on mount


  (0, _react.useEffect)(function () {
    (0, _incident.getAllIncident)().then(function (res) {
      var _res$data;

      if ((res === null || res === void 0 ? void 0 : (_res$data = res.data) === null || _res$data === void 0 ? void 0 : _res$data.length) > 0) {
        var _res$data$;

        setValue("incident", (_res$data$ = res.data[0]) === null || _res$data$ === void 0 ? void 0 : _res$data$.id);
      }

      setIncidentsList(res.data);
      setIsLoading(function (previous) {
        return _objectSpread(_objectSpread({}, previous), {}, {
          incident: false
        });
      });
    });
  }, [setValue]); // fetch hypotheses on incident selection

  (0, _react.useEffect)(function () {
    setHypothesisList([]);

    if (selectedIncident !== "new") {
      setIsLoading(function (previous) {
        return _objectSpread(_objectSpread({}, previous), {}, {
          hypothesis: true
        });
      });
      (0, _hypothesis.getAllHypothesisByIncident)(selectedIncident).then(function (res) {
        var _res$data2;

        if ((res === null || res === void 0 ? void 0 : (_res$data2 = res.data) === null || _res$data2 === void 0 ? void 0 : _res$data2.length) > 0) {
          var _res$data$2;

          setValue("hypothesis", (_res$data$2 = res.data[0]) === null || _res$data$2 === void 0 ? void 0 : _res$data$2.id);
        }

        setHypothesisList(res.data);
      }).finally(function () {
        setIsLoading(function (previous) {
          return _objectSpread(_objectSpread({}, previous), {}, {
            hypothesis: false
          });
        });
      });
    }
  }, [selectedIncident, setValue]);

  var onSubmit = function onSubmit(data) {
    setIsLoading(function (previous) {
      return _objectSpread(_objectSpread({}, previous), {}, {
        submit: true
      });
    });
    (0, _evidence.createEvidence)(user, _uuid.v4, data.hypothesis, JSON.stringify(selectedLogs), {
      type: data.type,
      description: data.description
    }).then(function () {
      callback(true);
    }).catch(function () {
      callback(false);
    }).finally(function () {
      setIsLoading(function (previous) {
        return _objectSpread(_objectSpread({}, previous), {}, {
          submit: false
        });
      });
    });
  };

  return /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", _objectSpread(_objectSpread({
    className: "py-7 ".concat(rest.className || "")
  }, rest), {}, {
    children: [/*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
      className: "text-xl font-medium text-gray-800 mb-6",
      children: ["Link", (selectedLogs === null || selectedLogs === void 0 ? void 0 : selectedLogs.length) > 1 ? " ".concat(selectedLogs === null || selectedLogs === void 0 ? void 0 : selectedLogs.length) : "", " log", (selectedLogs === null || selectedLogs === void 0 ? void 0 : selectedLogs.length) > 1 && "s", " to Incident"]
    }), /*#__PURE__*/(0, _jsxRuntime.jsxs)("form", {
      onSubmit: handleSubmit(onSubmit),
      children: [/*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
        className: "mb-4",
        children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_reactHookForm.Controller, {
          control: control,
          name: "description",
          render: function render(_ref2) {
            var field = _ref2.field;
            var onChange = field.onChange,
                value = field.value;
            return /*#__PURE__*/(0, _jsxRuntime.jsx)(_TextInput.TextInput, {
              label: "Evidence description",
              id: "description",
              className: "w-full",
              onChange: onChange,
              value: value
            });
          }
        }), /*#__PURE__*/(0, _jsxRuntime.jsx)("p", {
          className: "text-red-600 text-sm",
          children: (_errors$description = errors.description) === null || _errors$description === void 0 ? void 0 : _errors$description.message
        })]
      }), /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
        className: "mb-6",
        children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_Dropdown.Dropdown, {
          control: control,
          label: "Type",
          name: "type",
          className: "w-full",
          items: evidenceTypeItems
        }), /*#__PURE__*/(0, _jsxRuntime.jsx)("p", {
          className: "text-red-600 text-sm",
          children: (_errors$type = errors.type) === null || _errors$type === void 0 ? void 0 : _errors$type.message
        })]
      }), /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
        className: "w-full border-b mb-4"
      }), /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
        className: "mb-4",
        children: isLoading.incident ? /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
          className: "text-sm text-gray-400 mb-4",
          children: "Loading incidents..."
        }) : /*#__PURE__*/(0, _jsxRuntime.jsx)(_Dropdown.Dropdown, {
          control: control,
          label: "Incident",
          name: "incident",
          className: "w-full",
          items: getIncidentSelections(incidentsList)
        })
      }), selectedIncident !== "new" && (isLoading.hypothesis && (hypothesisList === null || hypothesisList === void 0 ? void 0 : hypothesisList.length) <= 0 ? /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
        className: "text-sm text-gray-400 mb-4",
        children: "Loading hypotheses..."
      }) : /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
        className: "mb-4",
        children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_Dropdown.Dropdown, {
          control: control,
          label: "Hypothesis",
          name: "hypothesis",
          className: "w-full",
          items: getHypothesisSelections(hypothesisList)
        })
      })), /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
        className: "flex justify-end",
        children: /*#__PURE__*/(0, _jsxRuntime.jsx)("button", {
          type: "submit",
          disabled: isLoading.incident || isLoading.hypothesis || isLoading.submit,
          className: "".concat(!isLoading.incident && !isLoading.hypothesis && !isLoading.submit ? "text-indigo-700 bg-indigo-100 hover:bg-indigo-200" : "text-gray-400 bg-gray-200", " inline-flex items-center px-2.5 py-1.5 border border-transparent text-xs font-medium rounded  focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"),
          children: isLoading.submit ? "Adding.." : "Add"
        })
      })]
    })]
  }));
}