'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 base$2 = require('./variations/_size/base.js');
var base = require('./variations/_view/base.js');
var base$1 = require('./variations/_helperTextView/base.js');
var Attach_styles = require('./Attach.styles.js');
var Attach_tokens = require('./Attach.tokens.js');
var useForkRef = require('../../hooks/useForkRef.js');
var AttachButton = require('./components/AttachButton/AttachButton.js');
var Cell = require('./ui/Cell/Cell.js');
var Dropdown = require('./ui/Dropdown/Dropdown.js');
var HiddenWidthHelper = require('./components/HiddenWidthHelper/HiddenWidthHelper.js');
var getFilenameParts = require('./utils/getFilenameParts.js');

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

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

var _excluded = ["flow", "buttonType", "hideButtonOnAttach", "hasAttachment", "multiple", "dropdownOptions", "acceptedFileFormats", "helperText", "size", "view", "helperTextView", "className", "style", "isLoading", "disabled", "id", "name", "customIcon", "onClick", "onChange", "onClear"];
var attachRoot = function attachRoot(Root) {
  return /*#__PURE__*/React.forwardRef(function (props, outerRef) {
    var _dropdownOptions$plac;
    var _props$flow = props.flow,
      flow = _props$flow === void 0 ? 'auto' : _props$flow,
      _props$buttonType = props.buttonType,
      buttonType = _props$buttonType === void 0 ? 'button' : _props$buttonType,
      _props$hideButtonOnAt = props.hideButtonOnAttach,
      hideButtonOnAttach = _props$hideButtonOnAt === void 0 ? false : _props$hideButtonOnAt,
      _props$hasAttachment = props.hasAttachment,
      hasAttachment = _props$hasAttachment === void 0 ? true : _props$hasAttachment,
      multiple = props.multiple,
      dropdownOptions = props.dropdownOptions,
      acceptedFileFormats = props.acceptedFileFormats,
      helperText = props.helperText,
      size = props.size,
      view = props.view,
      helperTextView = props.helperTextView,
      className = props.className,
      style = props.style,
      isLoading = props.isLoading,
      disabled = props.disabled,
      id = props.id,
      name = props.name,
      customIcon = props.customIcon,
      onClick = props.onClick,
      onChange = props.onChange,
      onClear = props.onClear,
      rest = _rollupPluginBabelHelpers.objectWithoutProperties(props, _excluded);
    var innerRef = React.useRef(null);
    var ref = useForkRef.useForkRef(outerRef, innerRef);
    var inputRef = React.useRef(null);
    var buttonRef = React.useRef(null);
    var fileWrapperWidthRef = React.useRef(null);
    var fileWrapperHelperRef = React.useRef(null);
    var cellHelperRefs = React.useRef({});
    var _useState = React.useState({}),
      _useState2 = _rollupPluginBabelHelpers.slicedToArray(_useState, 2),
      filesInfo = _useState2[0],
      setFilesInfo = _useState2[1];
    var _useState3 = React.useState(false),
      _useState4 = _rollupPluginBabelHelpers.slicedToArray(_useState3, 2),
      hasHiddenFiles = _useState4[0],
      setHasHiddenFiles = _useState4[1];
    var filesLength = Object.keys(filesInfo).length;
    var horizontalClass = flow === 'horizontal' ? Attach_tokens.classes.horizontal : undefined;
    var verticalClass = flow === 'vertical' ? Attach_tokens.classes.vertical : undefined;
    var autoClass = flow === 'auto' ? Attach_tokens.classes.auto : undefined;
    var withHelperTextClass = helperText ? Attach_tokens.classes.withHelperText : undefined;
    var accept = acceptedFileFormats === null || acceptedFileFormats === void 0 ? void 0 : acceptedFileFormats.join(',');
    var handleClick = function handleClick(e) {
      if (!inputRef.current) {
        return;
      }
      if (onClick) {
        onClick(e);
      }
      inputRef.current.click();
    };
    var handleChange = function handleChange(e) {
      var fileList = e.target.files;
      if (!fileList || fileList.length === 0) {
        return;
      }
      if (onChange) {
        onChange(e);
      }
      if (!hasAttachment) {
        return;
      }
      var fileArray = Array.from(fileList);
      var filesData = fileArray.reduce(function (acc, file, ind) {
        var fileKey = "".concat(ind, "_").concat(file.name);
        acc[fileKey] = getFilenameParts.getFilenameParts(file.name, size, customIcon);
        return acc;
      }, {});
      cellHelperRefs.current = {};
      setFilesInfo(filesData);
      setHasHiddenFiles(false);
    };
    var handleClear = function handleClear(fileKey) {
      if (!inputRef.current) {
        return;
      }
      if (onClear) {
        onClear(filesInfo[fileKey]);
      }
      setFilesInfo(function (prevFileInfo) {
        var updatedFilesInfo = _rollupPluginBabelHelpers.objectSpread2({}, prevFileInfo);
        delete updatedFilesInfo[fileKey];
        return updatedFilesInfo;
      });
      delete cellHelperRefs.current[fileKey];
      setHasHiddenFiles(false);
    };
    var getCellRef = function getCellRef(element, key) {
      if (element && cellHelperRefs !== null && cellHelperRefs !== void 0 && cellHelperRefs.current) {
        cellHelperRefs.current[key] = element;
      }
    };
    var updateHiddenFiles = function updateHiddenFiles() {
      var _window$getComputedSt;
      var newFilesInfo = _rollupPluginBabelHelpers.objectSpread2({}, filesInfo);
      if (!multiple || Object.keys(filesInfo).length === 0) {
        setHasHiddenFiles(false);
        return;
      }
      if (flow !== 'horizontal') {
        Object.keys(newFilesInfo).forEach(function (key) {
          newFilesInfo[key].isVisible = true;
        });
        setHasHiddenFiles(false);
        setFilesInfo(newFilesInfo);
        return;
      }
      if (!fileWrapperWidthRef.current || !fileWrapperHelperRef.current || !Object.keys(cellHelperRefs.current).length) {
        return;
      }
      var fileWrapper = fileWrapperWidthRef.current;
      var fileWrapperWidth = fileWrapper.clientWidth;
      var fileWrapperGap = parseInt((_window$getComputedSt = window.getComputedStyle(fileWrapper).columnGap) !== null && _window$getComputedSt !== void 0 ? _window$getComputedSt : 0, 10);
      var totalWidth = 0;
      var firstHidden = Object.entries(cellHelperRefs.current).findIndex(function (_ref) {
        var _ref2 = _rollupPluginBabelHelpers.slicedToArray(_ref, 2),
          cell = _ref2[1];
        totalWidth += cell.clientWidth + fileWrapperGap;
        if (totalWidth > fileWrapperWidth) {
          setHasHiddenFiles(true);
          return true;
        }
        return false;
      });
      var newKeys = Object.keys(newFilesInfo);
      var filesInfoVisibleKeys = firstHidden >= 0 ? newKeys.slice(0, firstHidden) : newKeys;
      var filesInfoHiddenKeys = firstHidden >= 0 ? newKeys.slice(firstHidden) : [];
      filesInfoVisibleKeys.forEach(function (key) {
        newFilesInfo[key].isVisible = true;
      });
      filesInfoHiddenKeys.forEach(function (key) {
        newFilesInfo[key].isVisible = false;
      });
      setFilesInfo(newFilesInfo);
    };
    React.useLayoutEffect(function () {
      updateHiddenFiles();
    }, [filesLength, flow, multiple]);
    React.useEffect(function () {
      if (flow !== 'horizontal' || !multiple) {
        return;
      }
      var observer = new ResizeObserver(function () {
        updateHiddenFiles();
      });
      if (innerRef.current) {
        observer.observe(innerRef.current);
      }
      return function () {
        return observer.disconnect();
      };
    }, [filesLength, flow, multiple]);
    var RootWrapper = function RootWrapper(_ref3) {
      var children = _ref3.children;
      return /*#__PURE__*/React__default.default.createElement(Root, {
        size: size,
        view: view
      }, children);
    };
    return /*#__PURE__*/React__default.default.createElement(Root, {
      className: index.cx(horizontalClass, verticalClass, autoClass, withHelperTextClass, className),
      style: style,
      size: size,
      view: view,
      helperTextView: helperTextView,
      ref: ref
    }, /*#__PURE__*/React__default.default.createElement(Attach_styles.StyledHiddenInput, {
      ref: inputRef,
      accept: accept,
      type: "file",
      id: id,
      name: name,
      multiple: multiple,
      onChange: handleChange
    }), (!hideButtonOnAttach || !filesLength) && /*#__PURE__*/React__default.default.createElement(Attach_styles.StyledAttachButtonWrapper, null, /*#__PURE__*/React__default.default.createElement(AttachButton.AttachButton, _rollupPluginBabelHelpers.extends({
      ref: buttonRef,
      buttonType: buttonType,
      isLoading: isLoading,
      disabled: disabled,
      onClick: handleClick
    }, rest)), helperText && /*#__PURE__*/React__default.default.createElement(Attach_styles.StyledHelperText, null, helperText)), (hasAttachment || hideButtonOnAttach) && Boolean(filesLength) && Object.values(filesInfo)[0].isVisible && /*#__PURE__*/React__default.default.createElement(React__default.default.Fragment, null, /*#__PURE__*/React__default.default.createElement(Attach_styles.FilesWrapper, {
      className: index.cx(horizontalClass, verticalClass, autoClass),
      applyOverflow: multiple && flow === 'horizontal'
    }, Object.entries(filesInfo).map(function (_ref4) {
      var _ref5 = _rollupPluginBabelHelpers.slicedToArray(_ref4, 2),
        key = _ref5[0],
        _ref5$ = _ref5[1],
        extension = _ref5$.extension,
        filenameWithoutExtension = _ref5$.filenameWithoutExtension,
        cellContentLeft = _ref5$.cellContentLeft,
        isVisible = _ref5$.isVisible;
      if (!isVisible) {
        return;
      }
      return /*#__PURE__*/React__default.default.createElement(Cell.CellUI, {
        key: key,
        filenameWithoutExtension: filenameWithoutExtension,
        extension: extension,
        size: size,
        cellContentLeft: cellContentLeft,
        multiple: multiple,
        flow: flow,
        onClick: function onClick() {
          return handleClear(key);
        }
      });
    }))), (hasAttachment || hideButtonOnAttach) && hasHiddenFiles && /*#__PURE__*/React__default.default.createElement(Dropdown.DropdownUI, _rollupPluginBabelHelpers.extends({
      rootWrapper: RootWrapper,
      size: size,
      filesInfo: filesInfo,
      customIcon: customIcon,
      handleClear: handleClear
    }, dropdownOptions, {
      placement: (_dropdownOptions$plac = dropdownOptions === null || dropdownOptions === void 0 ? void 0 : dropdownOptions.placement) !== null && _dropdownOptions$plac !== void 0 ? _dropdownOptions$plac : 'bottom'
    })), multiple && flow === 'horizontal' && /*#__PURE__*/React__default.default.createElement(HiddenWidthHelper.HiddenWidthHelper, {
      ref: fileWrapperWidthRef,
      hasHiddenFiles: hasHiddenFiles,
      size: size
    }), multiple && flow === 'horizontal' && (hasAttachment || hideButtonOnAttach) && Boolean(filesLength) && /*#__PURE__*/React__default.default.createElement(Attach_styles.FilesWrapper, {
      ref: fileWrapperHelperRef,
      className: index.cx(horizontalClass, Attach_tokens.classes.horizontalHidden)
    }, Object.entries(filesInfo).map(function (_ref6) {
      var _ref7 = _rollupPluginBabelHelpers.slicedToArray(_ref6, 2),
        key = _ref7[0],
        _ref7$ = _ref7[1],
        extension = _ref7$.extension,
        filenameWithoutExtension = _ref7$.filenameWithoutExtension,
        cellContentLeft = _ref7$.cellContentLeft;
      return /*#__PURE__*/React__default.default.createElement(Cell.CellUI, {
        key: key,
        ref: function ref(el) {
          return getCellRef(el, key);
        },
        filenameWithoutExtension: filenameWithoutExtension,
        extension: extension,
        size: size,
        cellContentLeft: cellContentLeft,
        multiple: multiple,
        flow: flow,
        isHelper: true
      });
    })));
  });
};
var attachConfig = {
  name: 'Attach',
  tag: 'div',
  layout: attachRoot,
  base: Attach_styles.base,
  variations: {
    view: {
      css: base.base
    },
    helperTextView: {
      css: base$1.base
    },
    size: {
      css: base$2.base
    }
  },
  defaults: {
    view: 'default',
    helperTextView: 'default',
    size: 'm'
  }
};

exports.attachConfig = attachConfig;
exports.attachRoot = attachRoot;
//# sourceMappingURL=Attach.js.map
