'use strict';

var _toConsumableArray = require('@babel/runtime/helpers/toConsumableArray');
var _slicedToArray = require('@babel/runtime/helpers/slicedToArray');
var _objectWithoutProperties = require('@babel/runtime/helpers/objectWithoutProperties');
var _asyncToGenerator = require('@babel/runtime/helpers/asyncToGenerator');
var _regeneratorRuntime = require('@babel/runtime/regenerator');
var shallow = require('zustand/shallow');
var React = require('react');
var neetoAtoms = require('@bigbinary/neeto-atoms');
var axios = require('axios');
var neetoCist = require('@bigbinary/neeto-cist');
var ramda = require('ramda');
var reactI18next = require('react-i18next');
var reactFileIcon_esm = require('./chunk-D3Unocnm.cjs.js');
var i18n = require('i18next');
var initializers = require('@bigbinary/neeto-commons-frontend/v2/initializers');
var constants = require('./chunk-2HrSPdAV.cjs.js');
require('@bigbinary/neeto-icons/LeftAlign');
require('@bigbinary/neeto-icons/CenterAlign');
require('@bigbinary/neeto-icons/RightAlign');
require('@bigbinary/neeto-icons/Delete');
require('@bigbinary/neeto-icons/CustomSize');
require('@bigbinary/neeto-icons/BorderDisable');
require('@bigbinary/neeto-icons/BorderEnable');
require('@bigbinary/neeto-icons/AspectRatio11');
require('@bigbinary/neeto-icons/AspectRatio169');
require('@bigbinary/neeto-icons/AspectRatio916');
require('@bigbinary/neeto-icons/AspectRatio43');
require('@bigbinary/neeto-icons/AspectRatio32');
var yup = require('yup');
var _defineProperty = require('@babel/runtime/helpers/defineProperty');
var jsxRuntime = require('react/jsx-runtime');

function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }

function _interopNamespace(e) {
  if (e && e.__esModule) return e;
  var n = Object.create(null);
  if (e) {
    Object.keys(e).forEach(function (k) {
      if (k !== 'default') {
        var d = Object.getOwnPropertyDescriptor(e, k);
        Object.defineProperty(n, k, d.get ? d : {
          enumerable: true,
          get: function () { return e[k]; }
        });
      }
    });
  }
  n.default = e;
  return Object.freeze(n);
}

var _toConsumableArray__default = /*#__PURE__*/_interopDefault(_toConsumableArray);
var _slicedToArray__default = /*#__PURE__*/_interopDefault(_slicedToArray);
var _objectWithoutProperties__default = /*#__PURE__*/_interopDefault(_objectWithoutProperties);
var _asyncToGenerator__default = /*#__PURE__*/_interopDefault(_asyncToGenerator);
var _regeneratorRuntime__default = /*#__PURE__*/_interopDefault(_regeneratorRuntime);
var axios__default = /*#__PURE__*/_interopDefault(axios);
var yup__namespace = /*#__PURE__*/_interopNamespace(yup);
var _defineProperty__default = /*#__PURE__*/_interopDefault(_defineProperty);

var DEFAULT_FILE_UPLOAD_CONFIG = {
  directUploadEndpoint: constants.DIRECT_UPLOAD_ENDPOINT,
  restrictions: {
    maxFileSize: initializers.globalProps.endUserUploadedFileSizeLimitInMb * 1024 * 1024
  }
};
var ATTACHMENT_OPTIONS = {
  OPEN_IN_NEW_TAB: i18n.t("neetoEditor.common.openInNewTab"),
  DOWNLOAD: i18n.t("neetoEditor.common.download"),
  RENAME: i18n.t("neetoEditor.attachments.rename"),
  DELETE: i18n.t("neetoEditor.menu.delete")
};
var ATTACHMENTS_PREVIEW_DATA_CY = "ne-attachments-preview-content";

var MAX_VIDEO_SIZE = 100 * 1024 * 1024; // 100 MB

var FILE_SIZE_UNITS = ["B", "KB", "MB", "GB"];
var ALLOWED_IMAGE_TYPES = [".jpg", ".jpeg", ".png", ".gif"];
var ALLOWED_VIDEO_TYPES = [".mp4", ".mov", ".avi", ".mkv"];
var DEFAULT_IMAGE_UPLOAD_CONFIG = {
  directUploadEndpoint: constants.DIRECT_UPLOAD_ENDPOINT,
  restrictions: {
    maxNumberOfFiles: 5,
    maxFileSize: initializers.globalProps.endUserUploadedFileSizeLimitInMb * 1024 * 1024,
    allowedFileTypes: ALLOWED_IMAGE_TYPES
  }
};
var DEFAULT_VIDEO_UPLOAD_CONFIG = {
  directUploadEndpoint: constants.DIRECT_UPLOAD_ENDPOINT,
  restrictions: {
    maxNumberOfFiles: 5,
    maxFileSize: MAX_VIDEO_SIZE,
    allowedFileTypes: ALLOWED_VIDEO_TYPES
  }
};
var VIDEO_EMBED_FORM_VALIDATION_SCHEMA = yup__namespace.object().shape({
  url: yup__namespace.string().required(i18n.t("neetoEditor.error.fieldRequired")).matches(constants.URL_REGEXP, i18n.t("neetoEditor.error.invalidUrl"))
});
var DEFAULT_ASPECT_RATIO = "16/9";

var convertToFileSize = function convertToFileSize() {
  var size = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 10 * 1024 * 1024;
  var fileSize = size;
  var i = 0;
  while (fileSize >= 1024 && i < FILE_SIZE_UNITS.length) {
    fileSize /= 1024;
    ++i;
  }
  return "".concat(fileSize.toFixed(1), " ").concat(FILE_SIZE_UNITS[i]);
};
var getTabs = function getTabs(mediaUploader) {
  if (mediaUploader.video) {
    return [{
      title: "Upload",
      key: "local"
    }, {
      title: "Embed",
      key: "embed"
    }];
  }
  return [];
};

var getFileExtension = function getFileExtension(filename) {
  if (!filename) return "";
  var parts = filename.split(".");
  return parts.length > 1 ? ".".concat(parts.pop()) : "";
};
var showWarningToastr = function showWarningToastr(_ref) {
  var selectedFiles = _ref.selectedFiles,
    initialFiles = _ref.initialFiles,
    config = _ref.config,
    largeFilesCount = _ref.largeFilesCount,
    unSupportedFilesCount = _ref.unSupportedFilesCount;
  var _config$restrictions = config.restrictions,
    maxNumberOfFiles = _config$restrictions.maxNumberOfFiles,
    maxFileSize = _config$restrictions.maxFileSize;
  if (unSupportedFilesCount > 0 || largeFilesCount > 0) {
    if (unSupportedFilesCount > 0) {
      neetoAtoms.Toastr.error(i18n.t("neetoEditor.error.fileNotAllowed"));
    }
    if (largeFilesCount > 0) {
      neetoAtoms.Toastr.error(i18n.t("neetoEditor.error.fileIsTooLarge", {
        maxFileSize: convertToFileSize(maxFileSize)
      }));
    }
  } else if (selectedFiles.length < initialFiles.length) {
    neetoAtoms.Toastr.warning(i18n.t("neetoEditor.attachments.maxNumberOfFiles", {
      entity: maxNumberOfFiles
    }));
  }
};
var shouldAddFile = function shouldAddFile(config) {
  return function (file) {
    var _config$restrictions2 = config.restrictions,
      maxFileSize = _config$restrictions2.maxFileSize,
      allowedFileTypes = _config$restrictions2.allowedFileTypes;
    if (neetoCist.isPresent(maxFileSize) && file.size > maxFileSize) {
      return {
        canAdd: false
      };
    }
    if (neetoCist.isPresent(allowedFileTypes)) {
      var fileExtension = getFileExtension(file.name);
      var mimeType = file.type;
      var extensionAllowed = allowedFileTypes.includes(fileExtension);
      var mimeAllowed = allowedFileTypes.includes(mimeType);
      var canAdd = extensionAllowed || mimeAllowed;
      return {
        canAdd: canAdd,
        isUnsupportedFile: !canAdd
      };
    }
    return {
      canAdd: true
    };
  };
};
var selectFiles = function selectFiles(_ref2) {
  var previousAttachmentsCount = _ref2.previousAttachmentsCount,
    config = _ref2.config,
    files = _ref2.files;
  var addedFilesCount = 0,
    largeFilesCount = 0,
    unSupportedFilesCount = 0;
  var fallbackMaxNumberOfFiles = previousAttachmentsCount + files.length;
  var _config$restrictions$ = config.restrictions.maxNumberOfFiles,
    maxNumberOfFiles = _config$restrictions$ === void 0 ? fallbackMaxNumberOfFiles : _config$restrictions$;
  var canAddFile = shouldAddFile(config);
  var remainingAttachments = maxNumberOfFiles - previousAttachmentsCount;
  if (remainingAttachments <= 0) {
    neetoAtoms.Toastr.warning(i18n.t("neetoEditor.attachments.maxNumberOfFiles", {
      entity: maxNumberOfFiles
    }));
    return [];
  }
  var selectedFiles = files.filter(function (file) {
    var _canAddFile = canAddFile(file),
      canAdd = _canAddFile.canAdd,
      isUnsupportedFile = _canAddFile.isUnsupportedFile;
    if (canAdd && addedFilesCount + 1 <= remainingAttachments) {
      addedFilesCount += 1;
      return true;
    }
    if (isUnsupportedFile) unSupportedFilesCount += 1;else if (!canAdd) largeFilesCount += 1;
    return false;
  });
  showWarningToastr({
    selectedFiles: selectedFiles,
    initialFiles: files,
    config: config,
    unSupportedFilesCount: unSupportedFilesCount,
    largeFilesCount: largeFilesCount
  });
  return selectedFiles;
};

var _excluded = ["data"];
var uploadControllers = {};
var useFileUploader = function useFileUploader(_ref) {
  var config = _ref.config,
    _ref$attachments = _ref.attachments,
    previousAttachments = _ref$attachments === void 0 ? [] : _ref$attachments,
    _ref$setIsUploadingOn = _ref.setIsUploadingOnHost,
    setIsUploadingOnHost = _ref$setIsUploadingOn === void 0 ? neetoCist.noop : _ref$setIsUploadingOn;
  var contextIdRef = React.useRef(reactFileIcon_esm.getRandomString());
  var _useTranslation = reactI18next.useTranslation(),
    t = _useTranslation.t;
  var contextId = contextIdRef.current;
  var _useFileUploadStore = reactFileIcon_esm.useFileUploadStore(function (store) {
      return {
        addFiles: store["addFiles"],
        getNextQueuedFile: store["getNextQueuedFile"],
        updateFileStatus: store["updateFileStatus"],
        removeFilesFromQueue: store["removeFilesFromQueue"],
        setIsUploading: store["setIsUploading"],
        updateFileUploadProgress: store["updateFileUploadProgress"],
        removeFile: store["removeFile"]
      };
    }, shallow.shallow),
    addFilesToStore = _useFileUploadStore.addFiles,
    getNextQueuedFile = _useFileUploadStore.getNextQueuedFile,
    updateFileStatus = _useFileUploadStore.updateFileStatus,
    removeFilesFromQueue = _useFileUploadStore.removeFilesFromQueue,
    setIsUploading = _useFileUploadStore.setIsUploading,
    updateFileUploadProgress = _useFileUploadStore.updateFileUploadProgress,
    removeFile = _useFileUploadStore.removeFile;
  var _useFileUploadStore2 = reactFileIcon_esm.useFileUploadStore(function (store) {
      var _store$contextId, _store$contextId2;
      return {
        files: (_store$contextId = store[contextId]) === null || _store$contextId === void 0 ? void 0 : _store$contextId["files"],
        isUploading: (_store$contextId2 = store[contextId]) === null || _store$contextId2 === void 0 ? void 0 : _store$contextId2["isUploading"]
      };
    }, shallow.shallow),
    _useFileUploadStore2$ = _useFileUploadStore2.files,
    files = _useFileUploadStore2$ === void 0 ? [] : _useFileUploadStore2$,
    isUploading = _useFileUploadStore2.isUploading;
  var handleUploadProgress = function handleUploadProgress(xhr, file) {
    if (!xhr.event.lengthComputable) return;
    var bytesUploaded = xhr.loaded;
    var bytesTotal = xhr.total;
    var progress = Math.round(bytesUploaded / bytesTotal * 100);
    updateFileUploadProgress(contextId, file.id, progress);
  };
  var uploadFile = /*#__PURE__*/function () {
    var _ref2 = _asyncToGenerator__default.default(/*#__PURE__*/_regeneratorRuntime__default.default.mark(function _callee(file) {
      var upload, _data$signed_id, _data$blob_url, _data$content_type, _yield$upload$create, _yield$upload$create$, data, response;
      return _regeneratorRuntime__default.default.wrap(function _callee$(_context) {
        while (1) switch (_context.prev = _context.next) {
          case 0:
            upload = new reactFileIcon_esm.DirectUpload({
              file: file.data,
              url: config.directUploadEndpoint,
              progress: function progress(xhr) {
                return handleUploadProgress(xhr, file);
              }
            });
            uploadControllers[file.id] = upload;
            _context.prev = 2;
            _context.next = 5;
            return upload.create();
          case 5:
            _yield$upload$create = _context.sent;
            _yield$upload$create$ = _yield$upload$create.data;
            data = _yield$upload$create$ === void 0 ? {} : _yield$upload$create$;
            response = _objectWithoutProperties__default.default(_yield$upload$create, _excluded);
            updateFileStatus(contextId, file.id, reactFileIcon_esm.FILE_UPLOAD_STATUS.UPLOADED);
            return _context.abrupt("return", {
              id: file.id,
              filename: file.filename,
              signedId: (_data$signed_id = data.signed_id) !== null && _data$signed_id !== void 0 ? _data$signed_id : response.signed_id,
              url: (_data$blob_url = data.blob_url) !== null && _data$blob_url !== void 0 ? _data$blob_url : response.blob_url,
              contentType: (_data$content_type = data.content_type) !== null && _data$content_type !== void 0 ? _data$content_type : response.content_type
            });
          case 13:
            _context.prev = 13;
            _context.t0 = _context["catch"](2);
            if (!axios__default.default.isCancel(_context.t0)) {
              neetoAtoms.Toastr.error(t("neetoEditor.error.uploadFileFailed"));
            }
            // eslint-disable-next-line no-console
            console.error("Attachment upload failed", _context.t0);
            removeFile(contextId, file.id);
            return _context.abrupt("return", null);
          case 19:
          case "end":
            return _context.stop();
        }
      }, _callee, null, [[2, 13]]);
    }));
    return function uploadFile(_x) {
      return _ref2.apply(this, arguments);
    };
  }();
  var _handleUploadFiles = /*#__PURE__*/function () {
    var _ref3 = _asyncToGenerator__default.default(/*#__PURE__*/_regeneratorRuntime__default.default.mark(function _callee2() {
      var queuedFile, _yield$Promise$all, _yield$Promise$all2, uploadedFile, remainingUploadedFiles, uploadedFiles, uploadedFileIds;
      return _regeneratorRuntime__default.default.wrap(function _callee2$(_context2) {
        while (1) switch (_context2.prev = _context2.next) {
          case 0:
            queuedFile = getNextQueuedFile(contextId);
            if (!neetoCist.isNotPresent(queuedFile)) {
              _context2.next = 5;
              break;
            }
            setIsUploading(contextId, false);
            setIsUploadingOnHost(false);
            return _context2.abrupt("return", []);
          case 5:
            updateFileStatus(contextId, queuedFile.id, reactFileIcon_esm.FILE_UPLOAD_STATUS.UPLOADING);
            _context2.next = 8;
            return Promise.all([uploadFile(queuedFile), _handleUploadFiles()]);
          case 8:
            _yield$Promise$all = _context2.sent;
            _yield$Promise$all2 = _slicedToArray__default.default(_yield$Promise$all, 2);
            uploadedFile = _yield$Promise$all2[0];
            remainingUploadedFiles = _yield$Promise$all2[1];
            uploadedFiles = [uploadedFile].concat(_toConsumableArray__default.default(remainingUploadedFiles));
            uploadedFileIds = ramda.pluck("id", uploadedFiles);
            removeFilesFromQueue(contextId, uploadedFileIds);
            uploadControllers = ramda.omit(uploadedFileIds, uploadControllers);
            return _context2.abrupt("return", uploadedFiles.filter(neetoCist.isNot(null)));
          case 17:
          case "end":
            return _context2.stop();
        }
      }, _callee2);
    }));
    return function handleUploadFiles() {
      return _ref3.apply(this, arguments);
    };
  }();
  var uploadFiles = function uploadFiles() {
    setIsUploading(contextId, true);
    setIsUploadingOnHost(true);
    return _handleUploadFiles();
  };
  var addFiles = function addFiles(addedFiles) {
    var selectedFiles = selectFiles({
      previousAttachmentsCount: previousAttachments.length,
      config: config,
      files: Array.from(addedFiles)
    }).map(function (file) {
      return {
        id: neetoCist.hyphenate("".concat(file.name.toLowerCase(), "-").concat(Date.now())),
        data: file,
        filename: file.name,
        signedId: "awaiting",
        url: "",
        type: file.type,
        status: reactFileIcon_esm.FILE_UPLOAD_STATUS.QUEUED
      };
    });
    addFilesToStore(contextId, selectedFiles);
  };
  var cancelUpload = function cancelUpload(fileId) {
    var _uploadControllers$fi, _uploadControllers$fi2;
    (_uploadControllers$fi = uploadControllers[fileId]) === null || _uploadControllers$fi === void 0 || (_uploadControllers$fi2 = _uploadControllers$fi.abort) === null || _uploadControllers$fi2 === void 0 || _uploadControllers$fi2.call(_uploadControllers$fi);
    removeFile(contextId, fileId);
  };
  return {
    addFiles: addFiles,
    uploadFiles: uploadFiles,
    queuedFiles: files,
    cancelUpload: cancelUpload,
    isUploading: isUploading
  };
};

function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), true).forEach(function (r) { _defineProperty__default.default(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
var File = function File(_ref) {
  var fileName = _ref.fileName,
    className = _ref.className;
  var extension = fileName.match(/([^.]+)$/) & [1];
  return /*#__PURE__*/jsxRuntime.jsx("div", {
    className: className,
    children: /*#__PURE__*/jsxRuntime.jsx(reactFileIcon_esm.FileIcon, _objectSpread({
      extension: extension,
      labelColor: "#4558f9"
    }, reactFileIcon_esm.defaultStyles[extension]))
  });
};

exports.ALLOWED_IMAGE_TYPES = ALLOWED_IMAGE_TYPES;
exports.ALLOWED_VIDEO_TYPES = ALLOWED_VIDEO_TYPES;
exports.ATTACHMENTS_PREVIEW_DATA_CY = ATTACHMENTS_PREVIEW_DATA_CY;
exports.ATTACHMENT_OPTIONS = ATTACHMENT_OPTIONS;
exports.DEFAULT_ASPECT_RATIO = DEFAULT_ASPECT_RATIO;
exports.DEFAULT_FILE_UPLOAD_CONFIG = DEFAULT_FILE_UPLOAD_CONFIG;
exports.DEFAULT_IMAGE_UPLOAD_CONFIG = DEFAULT_IMAGE_UPLOAD_CONFIG;
exports.DEFAULT_VIDEO_UPLOAD_CONFIG = DEFAULT_VIDEO_UPLOAD_CONFIG;
exports.File = File;
exports.VIDEO_EMBED_FORM_VALIDATION_SCHEMA = VIDEO_EMBED_FORM_VALIDATION_SCHEMA;
exports.convertToFileSize = convertToFileSize;
exports.getTabs = getTabs;
exports.useFileUploader = useFileUploader;
//# sourceMappingURL=chunk-CDAiAyof.cjs.js.map
