var _excluded = ["value", "disabled", "multiple", "noClick", "noKeyboard", "onDragEnter", "onDragOver", "onDragLeave", "onDropRejected", "maxFileSize", "minFileSize", "maxFileNumber", "onDrop", "onDropAccepted"];
var _dropErrorsByReason;
function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); 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 = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
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 = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; if (null != _i) { var _s, _e, _x, _r, _arr = [], _n = !0, _d = !1; try { if (_x = (_i = _i.call(arr)).next, 0 === i) { if (Object(_i) !== _i) return; _n = !1; } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0); } catch (err) { _d = !0, _e = err; } finally { try { if (!_n && null != _i["return"] && (_r = _i["return"](), Object(_r) !== _r)) 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; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
import React from 'react';
import { useDropzone as useDropzoneBase } from 'react-dropzone';
import { useI18nContext } from '../_hooks/I18n';
import { partition } from '../_utils/partition';
import { MultipleErrors } from './Dropzone';
import { StyledErrorBannerDetails } from './Dropzone.styles';
import { dropErrors, fileRejectionReason } from './Dropzone.types';
var oneDropAtATimeRejectionReason = 'one-drop-at-a-time';
var dropErrorsByReason = (_dropErrorsByReason = {}, _defineProperty(_dropErrorsByReason, fileRejectionReason.maxFiles, dropErrors.fileAmount), _defineProperty(_dropErrorsByReason, fileRejectionReason.maxFileSize, dropErrors.maxFileSize), _defineProperty(_dropErrorsByReason, fileRejectionReason.minFileSize, dropErrors.minFileSize), _defineProperty(_dropErrorsByReason, fileRejectionReason.fileType, dropErrors.fileType), _dropErrorsByReason);
var getSizeInMB = function getSizeInMB(maxSize) {
  return maxSize / 10e5;
};

/**
 * WARNING:
 * Use ACCEPT prop carefully, because mime type determination is not reliable across platforms.
 * Details: https://github.com/react-dropzone/react-dropzone/tree/master/examples/accept#browser-limitations
 */
export var useDropzone = function useDropzone() {
  var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  var _ref$value = _ref.value,
    value = _ref$value === void 0 ? [] : _ref$value,
    _ref$disabled = _ref.disabled,
    disabled = _ref$disabled === void 0 ? false : _ref$disabled,
    _ref$multiple = _ref.multiple,
    multiple = _ref$multiple === void 0 ? false : _ref$multiple,
    _ref$noClick = _ref.noClick,
    noClick = _ref$noClick === void 0 ? true : _ref$noClick,
    _ref$noKeyboard = _ref.noKeyboard,
    noKeyboard = _ref$noKeyboard === void 0 ? true : _ref$noKeyboard,
    onDragEnter = _ref.onDragEnter,
    onDragOver = _ref.onDragOver,
    onDragLeave = _ref.onDragLeave,
    onDropRejected = _ref.onDropRejected,
    maxSize = _ref.maxFileSize,
    minSize = _ref.minFileSize,
    _ref$maxFileNumber = _ref.maxFileNumber,
    maxFileNumber = _ref$maxFileNumber === void 0 ? Infinity : _ref$maxFileNumber,
    _onDrop = _ref.onDrop,
    onDropAccepted = _ref.onDropAccepted,
    props = _objectWithoutProperties(_ref, _excluded);
  var I18n = useI18nContext();
  var _React$useState = React.useState([]),
    _React$useState2 = _slicedToArray(_React$useState, 2),
    acceptedFiles = _React$useState2[0],
    setAcceptedFiles = _React$useState2[1];
  var _React$useState3 = React.useState([]),
    _React$useState4 = _slicedToArray(_React$useState3, 2),
    fileRejections = _React$useState4[0],
    setFileRejections = _React$useState4[1];
  var maxFilesRemaining = maxFileNumber - value.length;
  var defaultDropError = {
    type: dropErrors.reset,
    title: '',
    message: ''
  };
  var dropErrorReducer = function dropErrorReducer(state, action) {
    var rejectedFiles = /*#__PURE__*/React.createElement(StyledErrorBannerDetails, null, fileRejections.map(function (_ref2) {
      var name = _ref2.file.name;
      return /*#__PURE__*/React.createElement("li", {
        key: name
      }, name);
    }));
    var title = I18n.t('core.dropzone.errorTitle');
    switch (action) {
      case dropErrors.oneFileAtATime:
        return {
          type: dropErrors.oneFileAtATime,
          title: '',
          message: I18n.t('core.dropzone.oneFileAtATimeError')
        };
      case dropErrors.fileAmount:
        return {
          type: dropErrors.fileAmount,
          title: title,
          message: I18n.t('core.dropzone.standaloneMaxFileNumberError', {
            maxFiles: maxFileNumber
          }),
          body: rejectedFiles
        };
      case dropErrors.fileType:
        return {
          type: dropErrors.fileType,
          title: title,
          message: I18n.t('core.dropzone.standaloneUnsupportedFileTypeError'),
          body: rejectedFiles
        };
      case dropErrors.maxFileSize:
        return {
          type: dropErrors.maxFileSize,
          title: title,
          message: I18n.t('core.dropzone.standaloneMaxFileSizeError', {
            sizeInMegabytes: getSizeInMB(maxSize)
          }),
          body: rejectedFiles
        };
      case dropErrors.minFileSize:
        return {
          type: dropErrors.minFileSize,
          title: title,
          message: I18n.t('core.dropzone.standaloneMinFileSizeError', {
            sizeInMegabytes: getSizeInMB(minSize)
          }),
          body: rejectedFiles
        };
      case dropErrors.multipleErrors:
        return {
          type: dropErrors.multipleErrors,
          title: title,
          message: I18n.t('core.dropzone.multipleErrorsMessage'),
          body: /*#__PURE__*/React.createElement(MultipleErrors, {
            fileRejections: fileRejections,
            maxFiles: maxFileNumber,
            maxSize: maxSize,
            minSize: minSize
          })
        };
      case dropErrors.reset:
        return _objectSpread({}, defaultDropError);
      default:
        return state;
    }
  };
  var withOneDropAtATimeError = function withOneDropAtATimeError(file) {
    return {
      file: file,
      errors: [{
        message: I18n.t('core.dropzone.oneDropAtATimeError'),
        code: oneDropAtATimeRejectionReason
      }]
    };
  };
  var _React$useReducer = React.useReducer(dropErrorReducer, _objectSpread({}, defaultDropError)),
    _React$useReducer2 = _slicedToArray(_React$useReducer, 2),
    dropError = _React$useReducer2[0],
    dispatchDropError = _React$useReducer2[1];
  var onDrop = React.useCallback(function (acceptedFiles, rejectedFiles, event) {
    dispatchDropError(dropErrors.reset);
    var droppedFiles = [].concat(_toConsumableArray(acceptedFiles), _toConsumableArray(rejectedFiles.map(function (rej) {
      return rej.file;
    })));
    if (!multiple && droppedFiles.length > 1) {
      dispatchDropError(dropErrors.oneFileAtATime);
      onDropRejected === null || onDropRejected === void 0 ? void 0 : onDropRejected(droppedFiles.map(withOneDropAtATimeError), event);
      return;
    }
    var allFilesWithRejections = [].concat(_toConsumableArray(acceptedFiles.map(function (file) {
      return {
        file: file,
        errors: []
      };
    })), _toConsumableArray(rejectedFiles)).map(function (_ref3, i) {
      var file = _ref3.file,
        errors = _ref3.errors;
      return {
        file: file,
        errors: i < maxFilesRemaining ? errors : [].concat(_toConsumableArray(errors), [{
          message: '',
          code: fileRejectionReason.maxFiles
        }])
      };
    });
    var _partition = partition(function (_ref4) {
        var errors = _ref4.errors;
        return errors.length === 0;
      }, allFilesWithRejections),
      _partition2 = _slicedToArray(_partition, 2),
      actualAcceptedFiles_ = _partition2[0],
      actualRejectedFiles = _partition2[1];
    var actualAcceptedFiles = actualAcceptedFiles_.map(function (_ref5) {
      var file = _ref5.file;
      return file;
    });
    _onDrop === null || _onDrop === void 0 ? void 0 : _onDrop(actualAcceptedFiles, actualRejectedFiles, event);
    setAcceptedFiles(actualAcceptedFiles);
    setFileRejections(actualRejectedFiles);
    if (actualAcceptedFiles.length) {
      onDropAccepted === null || onDropAccepted === void 0 ? void 0 : onDropAccepted(actualAcceptedFiles, event);
    }
    if (actualRejectedFiles.length) {
      onDropRejected === null || onDropRejected === void 0 ? void 0 : onDropRejected(actualRejectedFiles, event);
    }
    var errorCodes = actualRejectedFiles.flatMap(function (rejection) {
      return rejection.errors;
    }).map(function (error) {
      return error.code;
    });
    var hasMultipleErrors = new Set(_toConsumableArray(errorCodes)).size > 1;
    if (hasMultipleErrors) {
      dispatchDropError(dropErrors.multipleErrors);
    } else {
      dispatchDropError(dropErrorsByReason[errorCodes[0]]);
    }
  }, [_onDrop, maxFilesRemaining, onDropRejected, onDropAccepted, multiple]);
  var _useDropzoneBase = useDropzoneBase(_objectSpread(_objectSpread({}, props), {}, {
      disabled: disabled,
      minSize: minSize,
      maxSize: maxSize,
      multiple: multiple,
      onDragEnter: onDragEnter,
      onDragLeave: onDragLeave,
      onDragOver: onDragOver,
      onDrop: onDrop,
      noClick: noClick,
      noKeyboard: noKeyboard
    })),
    getRootProps = _useDropzoneBase.getRootProps,
    getInputProps = _useDropzoneBase.getInputProps,
    isDragActive = _useDropzoneBase.isDragActive,
    isFileDialogActive = _useDropzoneBase.isFileDialogActive,
    isDragReject = _useDropzoneBase.isDragReject,
    isFocused = _useDropzoneBase.isFocused,
    isDragAccept = _useDropzoneBase.isDragAccept,
    draggedFiles = _useDropzoneBase.draggedFiles,
    open = _useDropzoneBase.open,
    rootRef = _useDropzoneBase.rootRef,
    inputRef = _useDropzoneBase.inputRef;
  var dragError = React.useMemo(function () {
    var getFileTypeError = function getFileTypeError() {
      return isDragReject ? I18n.t('core.dropzone.incorrectFileTypeMessage', {
        count: draggedFiles.length
      }) : '';
    };
    var getFileAmountError = function getFileAmountError() {
      var fileLimit = multiple ? maxFilesRemaining : 1;
      var amountError = multiple ? I18n.t('core.dropzone.invalidAmountAttachments', {
        count: maxFileNumber
      }) : I18n.t('core.dropzone.incorrectFileNumber');
      return draggedFiles.length > fileLimit ? amountError : '';
    };
    return getFileAmountError() || getFileTypeError();
  }, [I18n, draggedFiles.length, maxFilesRemaining, isDragReject, maxFileNumber, multiple]);
  return {
    getRootProps: getRootProps,
    getInputProps: getInputProps,
    isDragActive: isDragActive,
    isFileDialogActive: isFileDialogActive,
    isDragReject: isDragReject,
    isFocused: isFocused,
    isDragAccept: isDragAccept,
    draggedFiles: draggedFiles,
    acceptedFiles: acceptedFiles,
    fileRejections: fileRejections,
    open: open,
    rootRef: rootRef,
    inputRef: inputRef,
    multiple: multiple,
    dragError: dragError,
    dropError: dropError,
    dispatchDropError: dispatchDropError,
    disabled: disabled
  };
};
//# sourceMappingURL=Dropzone.hooks.js.map