"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

var _typeof = require("@babel/runtime/helpers/typeof");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = FileUploaderDropContainer;

var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));

var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));

var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));

var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));

var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties"));

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

var _propTypes = _interopRequireDefault(require("prop-types"));

var _classnames = _interopRequireDefault(require("classnames"));

var _js = require("../../globals/js");

var _uniqueId = _interopRequireDefault(require("../../tools/uniqueId"));

var _excluded = ["accept", "className", "id", "disabled", "labelText", "multiple", "name", "onAddFiles", "role", "tabIndex"];

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; }

var prefix = _js.settings.prefix;

function FileUploaderDropContainer(props) {
  var _classNames2;

  var inputRef = (0, _react.useRef)();
  var accept = props.accept,
      className = props.className,
      id = props.id,
      disabled = props.disabled,
      labelText = props.labelText,
      multiple = props.multiple,
      name = props.name,
      onAddFiles = props.onAddFiles,
      role = props.role,
      tabIndex = props.tabIndex,
      other = (0, _objectWithoutProperties2.default)(props, _excluded);
  var uid = (0, _react.useRef)((0, _uniqueId.default)());

  var _useState = (0, _react.useState)(false),
      _useState2 = (0, _slicedToArray2.default)(_useState, 2),
      isActive = _useState2[0],
      setActive = _useState2[1];

  var labelClasses = (0, _classnames.default)("".concat(prefix, "--file-browse-btn"), (0, _defineProperty2.default)({}, "".concat(prefix, "--file-browse-btn--disabled"), disabled));
  var dropareaClasses = (0, _classnames.default)("".concat(prefix, "--file__drop-container"), (_classNames2 = {}, (0, _defineProperty2.default)(_classNames2, "".concat(prefix, "--file__drop-container--drag-over"), isActive), (0, _defineProperty2.default)(_classNames2, className, className), _classNames2));
  /**
   * Filters the array of added files based on file type restrictions
   * @param {Event} evt - Event object, used to get the list of files added
   */

  var validateFiles = function validateFiles(evt) {
    if (evt.type === 'drop') {
      var transferredFiles = (0, _toConsumableArray2.default)(evt.dataTransfer.files);

      if (!accept.length) {
        return transferredFiles;
      }

      var acceptedTypes = new Set(accept);
      return transferredFiles.filter(function (_ref) {
        var name = _ref.name,
            _ref$type = _ref.type,
            mimeType = _ref$type === void 0 ? '' : _ref$type;
        var fileExtensionRegExp = new RegExp(/\.[0-9a-z]+$/, 'i');
        var hasFileExtension = fileExtensionRegExp.test(name);

        if (!hasFileExtension) {
          return false;
        }

        var _name$match = name.match(fileExtensionRegExp),
            _name$match2 = (0, _slicedToArray2.default)(_name$match, 1),
            fileExtension = _name$match2[0];

        return acceptedTypes.has(mimeType) || acceptedTypes.has(fileExtension);
      });
    }

    return (0, _toConsumableArray2.default)(evt.target.files);
  };

  var handleChange = function handleChange(evt) {
    var addedFiles = validateFiles(evt);
    return onAddFiles(evt, {
      addedFiles: addedFiles
    });
  };

  return /*#__PURE__*/_react.default.createElement("div", {
    className: "".concat(prefix, "--file"),
    onDragOver: function onDragOver(evt) {
      evt.stopPropagation();
      evt.preventDefault();

      if (disabled) {
        return;
      }

      setActive(true);
      evt.dataTransfer.dropEffect = 'copy';
    },
    onDragLeave: function onDragLeave(evt) {
      evt.stopPropagation();
      evt.preventDefault();

      if (disabled) {
        return;
      }

      setActive(false);
      evt.dataTransfer.dropEffect = 'move';
    },
    onDrop: function onDrop(evt) {
      evt.stopPropagation();
      evt.preventDefault();

      if (disabled) {
        return;
      }

      setActive(false);
      handleChange(evt);
    }
  }, /*#__PURE__*/_react.default.createElement("label", (0, _extends2.default)({
    className: labelClasses,
    htmlFor: id || uid.current,
    tabIndex: tabIndex || 0,
    onKeyDown: function onKeyDown(evt) {
      /*if (matches(evt, [keys.Enter, keys.Space])) {
        inputRef.current.click();
      }*/
    }
  }, other), /*#__PURE__*/_react.default.createElement("div", {
    className: dropareaClasses,
    role: role || 'button'
  }, labelText, /*#__PURE__*/_react.default.createElement("input", {
    type: "file",
    id: id || uid.current,
    className: "".concat(prefix, "--file-input"),
    ref: inputRef,
    tabIndex: "-1",
    disabled: disabled,
    accept: accept,
    name: name,
    multiple: multiple,
    onChange: handleChange,
    onClick: function onClick(evt) {
      evt.target.value = null;
    }
  }))));
}

FileUploaderDropContainer.propTypes = {
  /**
   * Provide a custom className to be applied to the container node
   */
  className: _propTypes.default.string,

  /**
   * Provide a unique id for the underlying <input> node
   */
  id: _propTypes.default.string,

  /**
   * Provide the label text to be read by screen readers when interacting with
   * this control
   */
  labelText: _propTypes.default.string.isRequired,

  /**
   * Specify if the component should accept multiple files to upload
   */
  multiple: _propTypes.default.bool,

  /**
   * Provide a name for the underlying <input> node
   */
  name: _propTypes.default.string,

  /**
   * Provide an accessibility role for the <FileUploaderButton>
   */
  role: _propTypes.default.string,

  /**
   * Provide a custom tabIndex value for the <FileUploaderButton>
   */
  tabIndex: _propTypes.default.number,

  /**
   * Specify whether file input is disabled
   */
  disabled: _propTypes.default.bool,

  /**
   * Specify the types of files that this input should be able to receive
   */
  accept: _propTypes.default.arrayOf(_propTypes.default.string),

  /**
   * Event handler that is called after files are added to the uploader
   * The event handler signature looks like `onAddFiles(evt, { addedFiles })`
   */
  onAddFiles: _propTypes.default.func
};
FileUploaderDropContainer.defaultProps = {
  tabIndex: 0,
  labelText: 'Add file',
  multiple: false,
  onAddFiles: function onAddFiles() {},
  accept: []
};