"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.AddFile = void 0;
var _eui = require("@elastic/eui");
var _react = _interopRequireWildcard(require("react"));
var _common = require("@kbn/files-plugin/common");
var _sharedUxFileUpload = require("@kbn/shared-ux-file-upload");
var _constants = require("../../../common/constants");
var _files = require("../../../common/files");
var _common2 = require("../../../common");
var _use_cases_toast = require("../../common/use_cases_toast");
var _use_create_attachments = require("../../containers/use_create_attachments");
var _use_cases_context = require("../cases_context/use_cases_context");
var i18n = _interopRequireWildcard(require("./translations"));
var _use_on_refresh_case_view_page = require("../case_view/use_on_refresh_case_view_page");
var _api = require("../../containers/api");
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 AddFileComponent = ({
  caseId
}) => {
  const {
    owner,
    permissions
  } = (0, _use_cases_context.useCasesContext)();
  const {
    showDangerToast,
    showErrorToast,
    showSuccessToast
  } = (0, _use_cases_toast.useCasesToast)();
  const {
    isLoading,
    mutateAsync: createAttachments
  } = (0, _use_create_attachments.useCreateAttachments)();
  const refreshAttachmentsTable = (0, _use_on_refresh_case_view_page.useRefreshCaseViewPage)();
  const [isModalVisible, setIsModalVisible] = (0, _react.useState)(false);
  const closeModal = () => setIsModalVisible(false);
  const showModal = () => setIsModalVisible(true);
  const onError = (0, _react.useCallback)(error => {
    showErrorToast(error, {
      title: i18n.FAILED_UPLOAD
    });
  }, [showErrorToast]);
  const onUploadDone = (0, _react.useCallback)(async chosenFiles => {
    if (chosenFiles.length === 0) {
      showDangerToast(i18n.FAILED_UPLOAD);
      return;
    }
    const file = chosenFiles[0];
    try {
      var _file$fileJSON$extens, _file$fileJSON$mimeTy;
      await createAttachments({
        caseId,
        caseOwner: owner[0],
        attachments: [{
          type: _common2.AttachmentType.externalReference,
          externalReferenceId: file.id,
          externalReferenceStorage: {
            type: _common2.ExternalReferenceStorageType.savedObject,
            soType: _common.FILE_SO_TYPE
          },
          externalReferenceAttachmentTypeId: _constants.FILE_ATTACHMENT_TYPE,
          externalReferenceMetadata: {
            files: [{
              name: file.fileJSON.name,
              extension: (_file$fileJSON$extens = file.fileJSON.extension) !== null && _file$fileJSON$extens !== void 0 ? _file$fileJSON$extens : '',
              mimeType: (_file$fileJSON$mimeTy = file.fileJSON.mimeType) !== null && _file$fileJSON$mimeTy !== void 0 ? _file$fileJSON$mimeTy : '',
              created: file.fileJSON.created
            }]
          }
        }]
      });
      refreshAttachmentsTable();
      showSuccessToast(i18n.SUCCESSFUL_UPLOAD_FILE_NAME(file.fileJSON.name));
    } catch (error) {
      // error toast is handled inside  createAttachments

      // we need to delete the file if attachment creation failed
      return (0, _api.deleteFileAttachments)({
        caseId,
        fileIds: [file.id]
      });
    }
    closeModal();
  }, [caseId, createAttachments, owner, refreshAttachmentsTable, showDangerToast, showSuccessToast]);
  return permissions.create && permissions.update ? /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
    grow: false
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiButton, {
    "data-test-subj": "cases-files-add",
    iconType: "plusInCircle",
    isDisabled: isLoading,
    isLoading: isLoading,
    onClick: showModal
  }, i18n.ADD_FILE), isModalVisible && /*#__PURE__*/_react.default.createElement(_eui.EuiModal, {
    "data-test-subj": "cases-files-add-modal",
    onClose: closeModal
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiModalHeader, null, /*#__PURE__*/_react.default.createElement(_eui.EuiModalHeaderTitle, null, i18n.ADD_FILE)), /*#__PURE__*/_react.default.createElement(_eui.EuiModalBody, null, /*#__PURE__*/_react.default.createElement(_sharedUxFileUpload.FileUpload, {
    kind: (0, _files.constructFileKindIdByOwner)(owner[0]),
    onDone: onUploadDone,
    onError: onError,
    meta: {
      caseIds: [caseId],
      owner: [owner[0]]
    }
  })))) : null;
};
AddFileComponent.displayName = 'AddFile';
const AddFile = /*#__PURE__*/_react.default.memo(AddFileComponent);
exports.AddFile = AddFile;