'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var _rollupPluginBabelHelpers = require('../../_virtual/_rollupPluginBabelHelpers.js');
var React = require('react');
var index = require('../../utils/index.js');
var IconArrowBarDown = require('../_Icon/Icons/IconArrowBarDown.js');
var base = require('./variations/_view/base.js');
var base$1 = require('./variations/_size/base.js');
var base$2 = require('./variations/_disabled/base.js');
var Dropzone_styles = require('./Dropzone.styles.js');
var Dropzone_tokens = require('./Dropzone.tokens.js');
var useForkRef = require('../../hooks/useForkRef.js');
var useResizeObserver = require('../../hooks/useResizeObserver.js');
var getSizeValueFromProp = require('../../utils/getSizeValueFromProp.js');
var canUseDOM = require('../../utils/canUseDOM.js');

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

var React__default = /*#__PURE__*/_interopDefault(React);

var _IconArrowBarDown;
var _excluded = ["files", "className", "style", "accept", "multiple", "title", "description", "icon", "iconPlacement", "size", "view", "disabled", "stretch", "width", "height", "onDragEnter", "onDragLeave", "onDragOver", "onDrop", "validator", "onClick", "onChange", "onChoseFiles"];
var dropzoneRoot = function dropzoneRoot(Root) {
  return /*#__PURE__*/React.forwardRef(function (_ref, outerRef) {
    var files = _ref.files,
      className = _ref.className,
      style = _ref.style,
      accept = _ref.accept,
      multiple = _ref.multiple,
      title = _ref.title,
      description = _ref.description,
      icon = _ref.icon,
      _ref$iconPlacement = _ref.iconPlacement,
      iconPlacement = _ref$iconPlacement === void 0 ? 'left' : _ref$iconPlacement,
      size = _ref.size,
      view = _ref.view,
      disabled = _ref.disabled,
      stretch = _ref.stretch,
      width = _ref.width,
      height = _ref.height,
      onDragEnter = _ref.onDragEnter,
      onDragLeave = _ref.onDragLeave,
      onDragOver = _ref.onDragOver,
      onDrop = _ref.onDrop,
      validator = _ref.validator,
      onClick = _ref.onClick,
      onChange = _ref.onChange,
      onChoseFiles = _ref.onChoseFiles,
      rest = _rollupPluginBabelHelpers.objectWithoutProperties(_ref, _excluded);
    var _useState = React.useState(false),
      _useState2 = _rollupPluginBabelHelpers.slicedToArray(_useState, 2),
      isDropzoneActive = _useState2[0],
      setIsDropzoneActive = _useState2[1];
    var _useState3 = React.useState(title),
      _useState4 = _rollupPluginBabelHelpers.slicedToArray(_useState3, 2),
      innerTitle = _useState4[0],
      setInnerTitle = _useState4[1];
    var _useState5 = React.useState(description),
      _useState6 = _rollupPluginBabelHelpers.slicedToArray(_useState5, 2),
      innerDescription = _useState6[0],
      setInnerDescription = _useState6[1];
    var _useState7 = React.useState([]),
      _useState8 = _rollupPluginBabelHelpers.slicedToArray(_useState7, 2),
      innerFiles = _useState8[0],
      setInnerFiles = _useState8[1];
    var currentFiles = files !== undefined ? files : innerFiles;
    var inputRef = React.useRef(null);
    var forkInputRef = useForkRef.useForkRef(outerRef, inputRef);
    var contentRef = React.useRef(null);
    var iconWrapperRef = React.useRef(null);
    var iconRef = React.useRef(null);
    var contentWrapperRef = React.useRef(null);
    var titleRef = React.useRef(null);
    var titleHelperRef = React.useRef(null);
    var descriptionRef = React.useRef(null);
    var descriptionHelperRef = React.useRef(null);
    var innerWidth = width ? getSizeValueFromProp.getSizeValueFromProp(width) : 'fit-content';
    var innerHeight = height ? getSizeValueFromProp.getSizeValueFromProp(height) : 'fit-content';
    var isTitleString = typeof title === 'string';
    var isDescriptionString = typeof description === 'string';
    var processFiles = /*#__PURE__*/function () {
      var _ref2 = _rollupPluginBabelHelpers.asyncToGenerator(/*#__PURE__*/_rollupPluginBabelHelpers.regeneratorRuntime().mark(function _callee(rawFiles, callback, afterAction) {
        var files, res;
        return _rollupPluginBabelHelpers.regeneratorRuntime().wrap(function _callee$(_context) {
          while (1) switch (_context.prev = _context.next) {
            case 0:
              if (rawFiles !== null && rawFiles !== void 0 && rawFiles.length) {
                _context.next = 2;
                break;
              }
              return _context.abrupt("return");
            case 2:
              files = _rollupPluginBabelHelpers.toConsumableArray(rawFiles);
              res = {
                acceptedFiles: files
              };
              if (!validator) {
                _context.next = 8;
                break;
              }
              _context.next = 7;
              return validator === null || validator === void 0 ? void 0 : validator(files);
            case 7:
              res = _context.sent;
            case 8:
              if (!callback) {
                _context.next = 11;
                break;
              }
              _context.next = 11;
              return callback(res);
            case 11:
              if (afterAction) {
                afterAction();
              }
            case 12:
            case "end":
              return _context.stop();
          }
        }, _callee);
      }));
      return function processFiles(_x, _x2, _x3) {
        return _ref2.apply(this, arguments);
      };
    }();
    var handleDragEnter = function handleDragEnter(event) {
      if (disabled) {
        return;
      }
      event.preventDefault();
      event.stopPropagation();
      if (onDragEnter) {
        onDragEnter(event);
      }
      setIsDropzoneActive(true);
    };
    var handleDragLeave = function handleDragLeave(event) {
      if (disabled) {
        return;
      }
      event.preventDefault();
      if (onDragLeave) {
        onDragLeave(event);
      }
      setIsDropzoneActive(false);
    };
    var handleDragOver = function handleDragOver(event) {
      if (disabled) {
        return;
      }
      event.preventDefault();
      if (onDragOver) {
        onDragOver(event);
      }
      var rawFiles = event.dataTransfer.files;
      if (!isDropzoneActive && rawFiles && rawFiles.length > 0) {
        setIsDropzoneActive(true);
      }
    };
    var handleDrop = /*#__PURE__*/function () {
      var _ref3 = _rollupPluginBabelHelpers.asyncToGenerator(/*#__PURE__*/_rollupPluginBabelHelpers.regeneratorRuntime().mark(function _callee2(event) {
        var rawFiles, afterAction;
        return _rollupPluginBabelHelpers.regeneratorRuntime().wrap(function _callee2$(_context2) {
          while (1) switch (_context2.prev = _context2.next) {
            case 0:
              if (!disabled) {
                _context2.next = 2;
                break;
              }
              return _context2.abrupt("return");
            case 2:
              event.preventDefault();
              event.persist();
              rawFiles = event.dataTransfer.files;
              afterAction = function afterAction() {
                event.dataTransfer.clearData();
                setIsDropzoneActive(false);
              };
              _context2.next = 8;
              return processFiles(rawFiles, onDrop, afterAction);
            case 8:
            case "end":
              return _context2.stop();
          }
        }, _callee2);
      }));
      return function handleDrop(_x4) {
        return _ref3.apply(this, arguments);
      };
    }();
    var handleClick = function handleClick(event) {
      if (!inputRef.current || disabled) {
        return;
      }
      inputRef.current.click();
      if (onClick) {
        onClick(event);
      }
    };
    var handleChange = /*#__PURE__*/function () {
      var _ref4 = _rollupPluginBabelHelpers.asyncToGenerator(/*#__PURE__*/_rollupPluginBabelHelpers.regeneratorRuntime().mark(function _callee4(event) {
        var rawFiles;
        return _rollupPluginBabelHelpers.regeneratorRuntime().wrap(function _callee4$(_context4) {
          while (1) switch (_context4.prev = _context4.next) {
            case 0:
              if (!disabled) {
                _context4.next = 2;
                break;
              }
              return _context4.abrupt("return");
            case 2:
              if (onChange) {
                onChange(event);
              }
              rawFiles = event.target.files;
              _context4.next = 6;
              return processFiles(rawFiles, /*#__PURE__*/function () {
                var _ref5 = _rollupPluginBabelHelpers.asyncToGenerator(/*#__PURE__*/_rollupPluginBabelHelpers.regeneratorRuntime().mark(function _callee3(res) {
                  return _rollupPluginBabelHelpers.regeneratorRuntime().wrap(function _callee3$(_context3) {
                    while (1) switch (_context3.prev = _context3.next) {
                      case 0:
                        setInnerFiles(res.acceptedFiles);
                        if (!onChoseFiles) {
                          _context3.next = 4;
                          break;
                        }
                        _context3.next = 4;
                        return onChoseFiles(res);
                      case 4:
                      case "end":
                        return _context3.stop();
                    }
                  }, _callee3);
                }));
                return function (_x6) {
                  return _ref5.apply(this, arguments);
                };
              }());
            case 6:
            case "end":
              return _context4.stop();
          }
        }, _callee4);
      }));
      return function handleChange(_x5) {
        return _ref4.apply(this, arguments);
      };
    }();
    var truncateContent = function truncateContent() {
      if (!canUseDOM.canUseDOM || !(descriptionRef !== null && descriptionRef !== void 0 && descriptionRef.current) || !(contentWrapperRef !== null && contentWrapperRef !== void 0 && contentWrapperRef.current) || !(titleRef !== null && titleRef !== void 0 && titleRef.current) || !(titleHelperRef !== null && titleHelperRef !== void 0 && titleHelperRef.current) || !(iconRef !== null && iconRef !== void 0 && iconRef.current) || !(iconWrapperRef !== null && iconWrapperRef !== void 0 && iconWrapperRef.current) || !(contentRef !== null && contentRef !== void 0 && contentRef.current) || !(descriptionHelperRef !== null && descriptionHelperRef !== void 0 && descriptionHelperRef.current) || !width && !height) {
        return;
      }
      var contentHeight = contentRef.current.offsetHeight;
      var iconHeight = iconRef.current.offsetHeight;
      var iconWidth = iconPlacement === 'top' ? 0 : iconRef.current.offsetWidth;
      var titleHeight = titleRef.current.offsetHeight;
      var iconContentGap = iconPlacement === 'top' ? Number(window.getComputedStyle(iconWrapperRef.current).rowGap.replace('px', '')) : 0;
      var availableWidth = contentRef.current.offsetWidth - iconWidth - iconContentGap;
      var contentGap = Number(window.getComputedStyle(contentWrapperRef.current).rowGap.replace('px', ''));
      var titleFontWidth = Math.floor(titleHelperRef.current.offsetWidth);
      var titleFontHeight = Math.floor(titleHelperRef.current.offsetHeight);
      var descriptionFontWidth = Math.floor(descriptionHelperRef.current.offsetWidth);
      var descriptionFontHeight = Math.floor(descriptionHelperRef.current.offsetHeight);
      var titleAvailableHeight = contentHeight - iconHeight - iconContentGap - descriptionFontHeight - contentGap;
      var titleMaxChars = Math.floor(availableWidth / titleFontWidth * (titleAvailableHeight / titleFontHeight));
      var resTitleLength = 0;
      if (title && isTitleString) {
        var newTitle = title.length <= titleMaxChars ? title : "".concat(title.slice(0, titleMaxChars - 3), "...");
        resTitleLength = newTitle.length;
        setInnerTitle(newTitle);
      }
      var resultTitleHeight = Math.floor(titleFontHeight * titleFontWidth * resTitleLength / availableWidth);
      var descriptionAvailableHeight = titleAvailableHeight >= titleHeight + 2 * descriptionFontHeight ? contentHeight - resultTitleHeight - iconContentGap - contentGap : descriptionFontHeight;
      var descriptionMaxChars = Math.floor(availableWidth / descriptionFontWidth * (descriptionAvailableHeight / descriptionFontHeight));
      if (description && isDescriptionString) {
        var newDescription = description.length <= descriptionMaxChars ? description : "".concat(description.slice(0, descriptionMaxChars - 3), "...");
        setInnerDescription(newDescription);
      }
    };
    useResizeObserver.useResizeObserver(contentRef, truncateContent);
    React.useEffect(function () {
      truncateContent();
    }, [title, description, iconPlacement]);
    React.useEffect(function () {
      if (inputRef.current) {
        inputRef.current.value = '';
      }
    }, [currentFiles]);
    return /*#__PURE__*/React__default.default.createElement(Root, {
      className: index.cx(className, isDropzoneActive && Dropzone_tokens.classes.active, stretch && Dropzone_tokens.classes.stretch, disabled && Dropzone_tokens.classes.disabled),
      view: view,
      size: size,
      disabled: disabled,
      tabIndex: 0,
      style: _rollupPluginBabelHelpers.objectSpread2(_rollupPluginBabelHelpers.objectSpread2({}, style), {}, _rollupPluginBabelHelpers.defineProperty(_rollupPluginBabelHelpers.defineProperty({}, Dropzone_tokens.privateTokens.width, innerWidth), Dropzone_tokens.privateTokens.height, innerHeight))
    }, /*#__PURE__*/React__default.default.createElement(Dropzone_styles.DropzoneHandlerOverlay, {
      onDragEnter: handleDragEnter,
      onDragLeave: handleDragLeave,
      onDragOver: handleDragOver,
      onDrop: handleDrop,
      onClick: handleClick
    }), /*#__PURE__*/React__default.default.createElement(Dropzone_styles.Content, {
      ref: contentRef
    }, /*#__PURE__*/React__default.default.createElement(Dropzone_styles.IconWrapper, {
      ref: iconWrapperRef,
      className: index.cx(iconPlacement === 'top' && Dropzone_tokens.classes.verticalContentPlacing)
    }, /*#__PURE__*/React__default.default.createElement(Dropzone_styles.StyledIcon, {
      ref: iconRef
    }, icon || _IconArrowBarDown || (_IconArrowBarDown = /*#__PURE__*/React__default.default.createElement(IconArrowBarDown.IconArrowBarDown, {
      color: "inherit",
      size: "s"
    }))), /*#__PURE__*/React__default.default.createElement(Dropzone_styles.ContentWrapper, {
      ref: contentWrapperRef
    }, title && isTitleString ? /*#__PURE__*/React__default.default.createElement(React__default.default.Fragment, null, /*#__PURE__*/React__default.default.createElement(Dropzone_styles.Title, {
      ref: titleRef
    }, innerTitle), /*#__PURE__*/React__default.default.createElement(Dropzone_styles.TitleHelper, {
      ref: titleHelperRef
    }, "C")) : title, description && isDescriptionString ? /*#__PURE__*/React__default.default.createElement(React__default.default.Fragment, null, /*#__PURE__*/React__default.default.createElement(Dropzone_styles.Description, {
      ref: descriptionRef
    }, innerDescription), /*#__PURE__*/React__default.default.createElement(Dropzone_styles.DescriptionHelper, {
      ref: descriptionHelperRef
    }, "C")) : description))), /*#__PURE__*/React__default.default.createElement(Dropzone_styles.HiddenInput, _rollupPluginBabelHelpers.extends({
      ref: forkInputRef,
      type: "file",
      accept: accept,
      multiple: multiple,
      tabIndex: -1,
      onChange: handleChange
    }, rest)));
  });
};
var dropzoneConfig = {
  name: 'Dropzone',
  tag: 'div',
  layout: dropzoneRoot,
  base: Dropzone_styles.base,
  variations: {
    view: {
      css: base.base
    },
    size: {
      css: base$1.base
    },
    disabled: {
      css: base$2.base,
      attrs: true
    }
  },
  defaults: {
    view: 'default',
    size: 'm'
  }
};

exports.dropzoneConfig = dropzoneConfig;
exports.dropzoneRoot = dropzoneRoot;
