'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 getFilenameParts = require('./utils/getFilenameParts.js');
var useIsomorphicLayoutEffect = require('../../hooks/useIsomorphicLayoutEffect.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 canUseDOM = require('../../utils/canUseDOM.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", "files", "onClick", "onChange", "onClear"];
var syncInputFiles = function syncInputFiles(input, filesToSync) {
  if (!canUseDOM.canUseDOM) {
    return;
  }
  input.value = '';
  if (filesToSync.length > 0) {
    var dataTransfer = new DataTransfer();
    filesToSync.forEach(function (file) {
      return dataTransfer.items.add(file);
    });
    input.files = dataTransfer.files;
  }
};
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,
      files = props.files,
      onClick = props.onClick,
      onChange = props.onChange,
      onClear = props.onClear,
      rest = _rollupPluginBabelHelpers.objectWithoutProperties(props, _excluded);
    var innerRef = React.useRef(null);
    var localInputRef = React.useRef(null);
    var inputRef = useForkRef.useForkRef(outerRef, localInputRef);
    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),
      innerFilesInfo = _useState2[0],
      setInnerFilesInfo = _useState2[1];
    var _useState3 = React.useState(false),
      _useState4 = _rollupPluginBabelHelpers.slicedToArray(_useState3, 2),
      hasHiddenFiles = _useState4[0],
      setHasHiddenFiles = _useState4[1];
    var _useState5 = React.useState({}),
      _useState6 = _rollupPluginBabelHelpers.slicedToArray(_useState5, 2),
      visibilityMap = _useState6[0],
      setVisibilityMap = _useState6[1];
    var controlledFilesInfo = React.useMemo(function () {
      if (files === undefined) {
        return undefined;
      }
      return files.reduce(function (acc, file, ind) {
        var fileKey = "".concat(ind, "_").concat(file.name);
        acc[fileKey] = _rollupPluginBabelHelpers.objectSpread2(_rollupPluginBabelHelpers.objectSpread2({}, getFilenameParts.getFilenameParts(file.name, size, customIcon)), {}, {
          file: file
        });
        return acc;
      }, {});
    }, [files, size, customIcon]);
    var filesInfo = controlledFilesInfo !== undefined ? controlledFilesInfo : innerFilesInfo;
    var mergedFilesInfo = React.useMemo(function () {
      if (Object.keys(visibilityMap).length === 0) {
        return filesInfo;
      }
      var result = {};
      Object.entries(filesInfo).forEach(function (_ref) {
        var _ref2 = _rollupPluginBabelHelpers.slicedToArray(_ref, 2),
          key = _ref2[0],
          info = _ref2[1];
        result[key] = _rollupPluginBabelHelpers.objectSpread2(_rollupPluginBabelHelpers.objectSpread2({}, info), {}, {
          isVisible: visibilityMap[key] !== false
        });
      });
      return result;
    }, [filesInfo, visibilityMap]);
    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 (!localInputRef.current) {
        return;
      }
      if (onClick) {
        onClick(e);
      }
      localInputRef.current.click();
    };
    var handleChange = function handleChange(e) {
      var fileList = e.target.files;
      if (onChange) {
        onChange(e);
      }
      if (!fileList || fileList.length === 0) {
        return;
      }
      var fileArray = Array.from(fileList);
      if (!hasAttachment || files !== undefined) {
        if (localInputRef.current) {
          localInputRef.current.value = '';
        }
        return;
      }
      var filesData = fileArray.reduce(function (acc, file, ind) {
        var fileKey = "".concat(ind, "_").concat(file.name);
        acc[fileKey] = _rollupPluginBabelHelpers.objectSpread2(_rollupPluginBabelHelpers.objectSpread2({}, getFilenameParts.getFilenameParts(file.name, size, customIcon)), {}, {
          file: file
        });
        return acc;
      }, {});
      if (localInputRef.current) {
        syncInputFiles(localInputRef.current, fileArray);
      }
      cellHelperRefs.current = {};
      setInnerFilesInfo(filesData);
      setHasHiddenFiles(false);
    };
    var handleClear = function handleClear(fileKey) {
      if (!localInputRef.current) {
        return;
      }
      if (onClear) {
        onClear(filesInfo[fileKey]);
      }
      if (files !== undefined) {
        return;
      }
      var updatedFilesInfo = _rollupPluginBabelHelpers.objectSpread2({}, innerFilesInfo);
      delete updatedFilesInfo[fileKey];
      setInnerFilesInfo(updatedFilesInfo);
      delete cellHelperRefs.current[fileKey];
      syncInputFiles(localInputRef.current, Object.values(updatedFilesInfo).map(function (fi) {
        return fi.file;
      }));
    };
    var getCellRef = function getCellRef(element, key) {
      if (!(cellHelperRefs !== null && cellHelperRefs !== void 0 && cellHelperRefs.current)) {
        return;
      }
      if (element) {
        cellHelperRefs.current[key] = element;
      } else {
        delete cellHelperRefs.current[key];
      }
    };
    var updateHiddenFiles = function updateHiddenFiles() {
      var _window$getComputedSt;
      if (!multiple || Object.keys(filesInfo).length === 0) {
        setHasHiddenFiles(false);
        return;
      }
      if (flow !== 'horizontal') {
        setHasHiddenFiles(false);
        setVisibilityMap({});
        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 (_ref3) {
        var _ref4 = _rollupPluginBabelHelpers.slicedToArray(_ref3, 2),
          cell = _ref4[1];
        totalWidth += cell.clientWidth + fileWrapperGap;
        return totalWidth > fileWrapperWidth;
      });
      setHasHiddenFiles(firstHidden >= 0);
      var newKeys = Object.keys(filesInfo);
      var filesInfoHiddenKeys = firstHidden >= 0 ? newKeys.slice(firstHidden) : [];
      var newVisibilityMap = {};
      filesInfoHiddenKeys.forEach(function (key) {
        newVisibilityMap[key] = false;
      });
      setVisibilityMap(newVisibilityMap);
    };
    React.useEffect(function () {
      if (files === undefined || !localInputRef.current) {
        return;
      }
      syncInputFiles(localInputRef.current, files);
    }, [files]);
    useIsomorphicLayoutEffect.useIsomorphicLayoutEffect(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(_ref5) {
      var children = _ref5.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: innerRef
    }, /*#__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(mergedFilesInfo)[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(mergedFilesInfo).map(function (_ref6) {
      var _ref7 = _rollupPluginBabelHelpers.slicedToArray(_ref6, 2),
        key = _ref7[0],
        _ref7$ = _ref7[1],
        extension = _ref7$.extension,
        filenameWithoutExtension = _ref7$.filenameWithoutExtension,
        cellContentLeft = _ref7$.cellContentLeft,
        isVisible = _ref7$.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: mergedFilesInfo,
      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 (_ref8) {
      var _ref9 = _rollupPluginBabelHelpers.slicedToArray(_ref8, 2),
        key = _ref9[0],
        _ref9$ = _ref9[1],
        extension = _ref9$.extension,
        filenameWithoutExtension = _ref9$.filenameWithoutExtension,
        cellContentLeft = _ref9$.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;
