import _extends from "@babel/runtime/helpers/extends";
import _toConsumableArray from "@babel/runtime/helpers/toConsumableArray";
import _defineProperty from "@babel/runtime/helpers/defineProperty";
import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
import _objectWithoutProperties from "@babel/runtime/helpers/objectWithoutProperties";
var _excluded = ["accept", "className", "id", "disabled", "labelText", "multiple", "name", "onAddFiles", "role", "tabIndex"];

/**
 * Copyright IBM Corp. 2016, 2018
 *
 * This source code is licensed under the Apache-2.0 license found in the
 * LICENSE file in the root directory of this source tree.
 */
import React, { useRef, useState } from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import { settings } from '../../globals/js'; //import { keys, matches } from '../../internal/keyboard';

import uniqueId from '../../tools/uniqueId';
var prefix = settings.prefix;
export default function FileUploaderDropContainer(props) {
  var _classNames2;

  var inputRef = 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 = _objectWithoutProperties(props, _excluded);

  var uid = useRef(uniqueId());

  var _useState = useState(false),
      _useState2 = _slicedToArray(_useState, 2),
      isActive = _useState2[0],
      setActive = _useState2[1];

  var labelClasses = classNames("".concat(prefix, "--file-browse-btn"), _defineProperty({}, "".concat(prefix, "--file-browse-btn--disabled"), disabled));
  var dropareaClasses = classNames("".concat(prefix, "--file__drop-container"), (_classNames2 = {}, _defineProperty(_classNames2, "".concat(prefix, "--file__drop-container--drag-over"), isActive), _defineProperty(_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 = _toConsumableArray(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 = _slicedToArray(_name$match, 1),
            fileExtension = _name$match2[0];

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

    return _toConsumableArray(evt.target.files);
  };

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

  return /*#__PURE__*/React.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.createElement("label", _extends({
    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.createElement("div", {
    className: dropareaClasses,
    role: role || 'button'
  }, labelText, /*#__PURE__*/React.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.string,

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

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

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

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

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

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

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

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

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