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

var _yup = require("@hookform/resolvers/yup");

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

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

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

var _uuid = require("uuid");

var yup = _interopRequireWildcard(require("yup"));

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 _toast = require("../../Toast/toast");

var _data = require("../data");

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

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

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 _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 _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 validationSchema = yup.object({
  title: yup.string().required(),
  description: yup.string(),
  // communicator_id: yup.string().required(),
  // commander_id: yup.string().required(),
  // tracking: yup.string().email().required(),
  severity: yup.number().required(),
  status: yup.string().required(),
  type: yup.string().required()
}).required();

function IncidentCreate(_ref) {
  var _errors$title, _errors$description, _errors$severity, _errors$status, _errors$type;

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

  var navigate = (0, _reactRouterDom.useNavigate)();
  var user = (0, _context.useUser)();
  var location = (0, _reactRouterDom.useLocation)();

  var _useForm = (0, _reactHookForm.useForm)({
    defaultValues: {
      title: "",
      description: "",
      // tracking: "",
      severity: 0,
      status: "open",
      type: "issue"
    },
    resolver: (0, _yup.yupResolver)(validationSchema)
  }),
      control = _useForm.control,
      errors = _useForm.formState.errors,
      handleSubmit = _useForm.handleSubmit;

  var additionalFields = {
    id: "",
    created_by: "",
    communicator_id: "",
    commander_id: "",
    created_at: "now()",
    updated_at: "now()"
  };

  var onSubmit = function onSubmit(data) {
    var payload = _objectSpread(_objectSpread({}, data), additionalFields);

    payload.id = (0, _uuid.v4)();
    (0, _incident.createIncident)(user, payload).then(function (created) {
      (0, _hypothesis.createHypothesis)(user, (0, _uuid.v4)(), payload.id, {
        title: payload.title,
        type: "root",
        status: "possible"
      }).then(function (hypothesis) {
        var _hypothesis$data$;

        if (hypothesis !== null && hypothesis !== void 0 && (_hypothesis$data$ = hypothesis.data[0]) !== null && _hypothesis$data$ !== void 0 && _hypothesis$data$.id && evidence) {
          (0, _evidence.createEvidence)(user, (0, _uuid.v4)(), hypothesis.data[0].id, {
            lines: evidence === null || evidence === void 0 ? void 0 : evidence.lines,
            config_id: evidence === null || evidence === void 0 ? void 0 : evidence.configId,
            config_full: evidence === null || evidence === void 0 ? void 0 : evidence.config
          }, {
            description: evidence === null || evidence === void 0 ? void 0 : evidence.configName,
            type: evidence === null || evidence === void 0 ? void 0 : evidence.type
          });
        }
      });
      if (created) if (callback != null) {
        callback(created.data[0]);
      } else {
        navigate("/incidents/".concat(created.data[0].id), {
          replace: true
        });
      }
    }).catch(_toast.toastError);
  };

  return /*#__PURE__*/(0, _jsxRuntime.jsx)("div", _objectSpread(_objectSpread({
    className: "py-7 ".concat(rest.className || "")
  }, rest), {}, {
    children: /*#__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: "title",
          render: function render(_ref2) {
            var field = _ref2.field;
            var onChange = field.onChange,
                value = field.value;
            return /*#__PURE__*/(0, _jsxRuntime.jsx)(_TextInput.TextInput, {
              label: "Title",
              id: "title",
              className: "w-full",
              onChange: onChange,
              value: value
            });
          }
        }), /*#__PURE__*/(0, _jsxRuntime.jsx)("p", {
          className: "text-red-600 text-sm",
          children: (_errors$title = errors.title) === null || _errors$title === void 0 ? void 0 : _errors$title.message
        })]
      }), /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
        className: "mb-4",
        children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_reactHookForm.Controller, {
          control: control,
          name: "description",
          render: function render(_ref3) {
            var field = _ref3.field;
            var onChange = field.onChange,
                value = field.value;
            return /*#__PURE__*/(0, _jsxRuntime.jsx)(_TextInput.TextInput, {
              label: "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-4",
        children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_Dropdown.Dropdown, {
          control: control,
          label: "Severity",
          name: "severity",
          className: "w-full",
          items: _data.severityItems
        }), /*#__PURE__*/(0, _jsxRuntime.jsx)("p", {
          className: "text-red-600 text-sm",
          children: (_errors$severity = errors.severity) === null || _errors$severity === void 0 ? void 0 : _errors$severity.message
        })]
      }), /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
        className: "mb-4",
        children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_Dropdown.Dropdown, {
          control: control,
          label: "Status",
          name: "status",
          className: "w-full",
          items: _data.statusItems
        }), /*#__PURE__*/(0, _jsxRuntime.jsx)("p", {
          className: "text-red-600 text-sm",
          children: (_errors$status = errors.status) === null || _errors$status === void 0 ? void 0 : _errors$status.message
        })]
      }), /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
        className: "mb-4",
        children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_Dropdown.Dropdown, {
          control: control,
          label: "Type",
          name: "type",
          className: "w-full",
          items: _data.typeItems
        }), /*#__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: "flex justify-end",
        children: /*#__PURE__*/(0, _jsxRuntime.jsx)("button", {
          type: "submit",
          className: "inline-flex items-center px-2.5 py-1.5 border border-transparent text-xs font-medium rounded text-indigo-700 bg-indigo-100 hover:bg-indigo-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500",
          children: "Create"
        })
      })]
    })
  }));
}