"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.AddComment = void 0;
var _react = _interopRequireWildcard(require("react"));
var _eui = require("@elastic/eui");
var _styledComponents = _interopRequireDefault(require("styled-components"));
var _lodash = require("lodash");
var _hook_form_lib = require("@kbn/es-ui-shared-plugin/static/forms/hook_form_lib");
var _domain = require("../../../common/types/domain");
var _use_create_attachments = require("../../containers/use_create_attachments");
var _markdown_editor = require("../markdown_editor");
var _utils = require("../markdown_editor/utils");
var _utils2 = require("../utils");
var i18n = _interopRequireWildcard(require("./translations"));
var _schema = require("./schema");
var _insert_timeline = require("../insert_timeline");
var _use_cases_context = require("../cases_context/use_cases_context");
var _constants = require("../../../common/constants");
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (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; }
/*
 * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
 * or more contributor license agreements. Licensed under the Elastic License
 * 2.0; you may not use this file except in compliance with the Elastic License
 * 2.0.
 */

const MySpinner = (0, _styledComponents.default)(_eui.EuiLoadingSpinner)`
  position: absolute;
  top: 50%;
  left: 50%;
`;
const initialCommentValue = {
  comment: ''
};

/* eslint-disable react/no-unused-prop-types */

/* eslint-enable react/no-unused-prop-types */

const AddComment = /*#__PURE__*/_react.default.memo( /*#__PURE__*/(0, _react.forwardRef)(({
  id,
  caseId,
  onCommentPosted,
  onCommentSaving,
  showLoading = true,
  statusActionButton
}, ref) => {
  const editorRef = (0, _react.useRef)(null);
  const [focusOnContext, setFocusOnContext] = (0, _react.useState)(false);
  const {
    permissions,
    owner,
    appId
  } = (0, _use_cases_context.useCasesContext)();
  const {
    isLoading,
    mutate: createAttachments
  } = (0, _use_create_attachments.useCreateAttachments)();
  const draftStorageKey = (0, _utils.getMarkdownEditorStorageKey)(appId, caseId, id);
  const {
    form
  } = (0, _hook_form_lib.useForm)({
    defaultValue: initialCommentValue,
    options: {
      stripEmptyFields: false
    },
    schema: _schema.schema
  });
  const fieldName = 'comment';
  const {
    setFieldValue,
    reset,
    submit
  } = form;
  const [{
    comment
  }] = (0, _hook_form_lib.useFormData)({
    form,
    watch: [fieldName]
  });
  const addQuote = (0, _react.useCallback)(quote => {
    const addCarrots = quote.replace(new RegExp('\r?\n', 'g'), '\n> ');
    const val = `> ${addCarrots} \n\n`;
    setFieldValue(fieldName, `${comment}${comment.length > 0 ? '\n\n' : ''}${val}`);
    setFocusOnContext(true);
  }, [comment, setFieldValue]);
  const setComment = (0, _react.useCallback)(newComment => {
    setFieldValue(fieldName, newComment);
  }, [setFieldValue]);
  (0, _react.useImperativeHandle)(ref, () => ({
    addQuote,
    setComment,
    editor: editorRef.current
  }));
  const onSubmit = (0, _react.useCallback)(async () => {
    const {
      isValid,
      data
    } = await submit();
    if (isValid) {
      if (onCommentSaving != null) {
        onCommentSaving();
      }
      createAttachments({
        caseId,
        caseOwner: owner[0],
        attachments: [{
          ...data,
          type: _domain.AttachmentType.user
        }]
      }, {
        onSuccess: theCase => {
          onCommentPosted(theCase);
        }
      });
      reset({
        defaultValue: {}
      });
    }
    (0, _utils2.removeItemFromSessionStorage)(draftStorageKey);
  }, [submit, onCommentSaving, createAttachments, caseId, owner, onCommentPosted, reset, draftStorageKey]);

  /**
   * Focus on the text area when a quote has been added.
   *
   * The useEffect will run only when focusOnContext
   * changes.
   *
   * The useEffect is also called once one mount
   * where the comment is empty. We do not want to focus
   * in this scenario.
   *
   * Ideally we would like to put the
   * editorRef.current?.textarea?.focus(); inside the if (focusOnContext).
   * The reason this is not feasible is because when it sets the
   * focusOnContext to false a render will occur again and the
   * focus will be lost.
   *
   * We do not put the comment in the dependency list
   * because we do not want to focus when the user
   * is typing.
   */

  (0, _react.useEffect)(() => {
    if (!(0, _lodash.isEmpty)(comment)) {
      var _editorRef$current, _editorRef$current$te;
      (_editorRef$current = editorRef.current) === null || _editorRef$current === void 0 ? void 0 : (_editorRef$current$te = _editorRef$current.textarea) === null || _editorRef$current$te === void 0 ? void 0 : _editorRef$current$te.focus();
    }
    if (focusOnContext) {
      setFocusOnContext(false);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [focusOnContext]);
  const isDisabled = isLoading || !(comment !== null && comment !== void 0 && comment.trim().length) || comment.trim().length > _constants.MAX_COMMENT_LENGTH;
  return /*#__PURE__*/_react.default.createElement("span", {
    id: "add-comment-permLink"
  }, isLoading && showLoading && /*#__PURE__*/_react.default.createElement(MySpinner, {
    "data-test-subj": "loading-spinner",
    size: "xl"
  }), permissions.create && /*#__PURE__*/_react.default.createElement(_hook_form_lib.Form, {
    form: form
  }, /*#__PURE__*/_react.default.createElement(_hook_form_lib.UseField, {
    path: fieldName,
    component: _markdown_editor.MarkdownEditorForm,
    componentProps: {
      ref: editorRef,
      id,
      draftStorageKey,
      idAria: 'caseComment',
      isDisabled: isLoading,
      dataTestSubj: 'add-comment',
      placeholder: i18n.ADD_COMMENT_HELP_TEXT,
      bottomRightContent: /*#__PURE__*/_react.default.createElement(_eui.EuiFlexGroup, {
        gutterSize: "s",
        alignItems: "flexEnd",
        responsive: false,
        wrap: true
      }, statusActionButton && /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
        grow: false
      }, statusActionButton), /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
        grow: false
      }, /*#__PURE__*/_react.default.createElement(_eui.EuiButton, {
        "data-test-subj": "submit-comment",
        fill: true,
        iconType: "plusInCircle",
        isDisabled: isDisabled,
        isLoading: isLoading,
        onClick: onSubmit
      }, i18n.ADD_COMMENT)))
    }
  }), /*#__PURE__*/_react.default.createElement(_insert_timeline.InsertTimeline, {
    fieldName: "comment"
  })));
}));
exports.AddComment = AddComment;
AddComment.displayName = 'AddComment';