"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
function _export(target, all) {
    for(var name in all)Object.defineProperty(target, name, {
        enumerable: true,
        get: Object.getOwnPropertyDescriptor(all, name).get
    });
}
_export(exports, {
    get attachConfig () {
        return attachConfig;
    },
    get attachRoot () {
        return attachRoot;
    }
});
var _react = /*#__PURE__*/ _interop_require_wildcard(require("react"));
var _utils = require("../../utils");
var _hooks = require("../../hooks");
var _base = require("./variations/_size/base");
var _base1 = require("./variations/_view/base");
var _base2 = require("./variations/_helperTextView/base");
var _Attachstyles = require("./Attach.styles");
var _utils1 = require("./utils");
var _Attachtokens = require("./Attach.tokens");
var _components = require("./components");
var _ui = require("./ui");
function _array_like_to_array(arr, len) {
    if (len == null || len > arr.length) len = arr.length;
    for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
    return arr2;
}
function _array_with_holes(arr) {
    if (Array.isArray(arr)) return arr;
}
function _define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}
function _getRequireWildcardCache(nodeInterop) {
    if (typeof WeakMap !== "function") return null;
    var cacheBabelInterop = new WeakMap();
    var cacheNodeInterop = new WeakMap();
    return (_getRequireWildcardCache = function(nodeInterop) {
        return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
    })(nodeInterop);
}
function _interop_require_wildcard(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 = {
        __proto__: null
    };
    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;
}
function _iterable_to_array_limit(arr, i) {
    var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
    if (_i == null) return;
    var _arr = [];
    var _n = true;
    var _d = false;
    var _s, _e;
    try {
        for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
            _arr.push(_s.value);
            if (i && _arr.length === i) break;
        }
    } catch (err) {
        _d = true;
        _e = err;
    } finally{
        try {
            if (!_n && _i["return"] != null) _i["return"]();
        } finally{
            if (_d) throw _e;
        }
    }
    return _arr;
}
function _non_iterable_rest() {
    throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _object_spread(target) {
    for(var i = 1; i < arguments.length; i++){
        var source = arguments[i] != null ? arguments[i] : {};
        var ownKeys = Object.keys(source);
        if (typeof Object.getOwnPropertySymbols === "function") {
            ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
                return Object.getOwnPropertyDescriptor(source, sym).enumerable;
            }));
        }
        ownKeys.forEach(function(key) {
            _define_property(target, key, source[key]);
        });
    }
    return target;
}
function ownKeys(object, enumerableOnly) {
    var keys = Object.keys(object);
    if (Object.getOwnPropertySymbols) {
        var symbols = Object.getOwnPropertySymbols(object);
        if (enumerableOnly) {
            symbols = symbols.filter(function(sym) {
                return Object.getOwnPropertyDescriptor(object, sym).enumerable;
            });
        }
        keys.push.apply(keys, symbols);
    }
    return keys;
}
function _object_spread_props(target, source) {
    source = source != null ? source : {};
    if (Object.getOwnPropertyDescriptors) {
        Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
    } else {
        ownKeys(Object(source)).forEach(function(key) {
            Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
        });
    }
    return target;
}
function _object_without_properties(source, excluded) {
    if (source == null) return {};
    var target = {}, sourceKeys, key, i;
    if (typeof Reflect !== "undefined" && Reflect.ownKeys) {
        sourceKeys = Reflect.ownKeys(source);
        for(i = 0; i < sourceKeys.length; i++){
            key = sourceKeys[i];
            if (excluded.indexOf(key) >= 0) continue;
            if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
            target[key] = source[key];
        }
        return target;
    }
    target = _object_without_properties_loose(source, excluded);
    if (Object.getOwnPropertySymbols) {
        sourceKeys = Object.getOwnPropertySymbols(source);
        for(i = 0; i < sourceKeys.length; i++){
            key = sourceKeys[i];
            if (excluded.indexOf(key) >= 0) continue;
            if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
            target[key] = source[key];
        }
    }
    return target;
}
function _object_without_properties_loose(source, excluded) {
    if (source == null) return {};
    var target = {}, sourceKeys = Object.getOwnPropertyNames(source), key, i;
    for(i = 0; i < sourceKeys.length; i++){
        key = sourceKeys[i];
        if (excluded.indexOf(key) >= 0) continue;
        if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
        target[key] = source[key];
    }
    return target;
}
function _sliced_to_array(arr, i) {
    return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest();
}
function _unsupported_iterable_to_array(o, minLen) {
    if (!o) return;
    if (typeof o === "string") return _array_like_to_array(o, minLen);
    var n = Object.prototype.toString.call(o).slice(8, -1);
    if (n === "Object" && o.constructor) n = o.constructor.name;
    if (n === "Map" || n === "Set") return Array.from(n);
    if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
}
var attachRoot = function attachRoot(Root) {
    return /*#__PURE__*/ (0, _react.forwardRef)(function(props, outerRef) {
        var _ref;
        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_hideButtonOnAttach = props.hideButtonOnAttach, hideButtonOnAttach = _props_hideButtonOnAttach === void 0 ? false : _props_hideButtonOnAttach, _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 = _object_without_properties(props, [
            "flow",
            "buttonType",
            "hideButtonOnAttach",
            "hasAttachment",
            "multiple",
            "dropdownOptions",
            "acceptedFileFormats",
            "helperText",
            "size",
            "view",
            "helperTextView",
            "className",
            "style",
            "isLoading",
            "disabled",
            "id",
            "name",
            "customIcon",
            "onClick",
            "onChange",
            "onClear"
        ]);
        var innerRef = (0, _react.useRef)(null);
        var ref = (0, _hooks.useForkRef)(outerRef, innerRef);
        var inputRef = (0, _react.useRef)(null);
        var buttonRef = (0, _react.useRef)(null);
        var fileWrapperWidthRef = (0, _react.useRef)(null);
        var fileWrapperHelperRef = (0, _react.useRef)(null);
        var cellHelperRefs = (0, _react.useRef)({});
        var _useState = _sliced_to_array((0, _react.useState)({}), 2), filesInfo = _useState[0], setFilesInfo = _useState[1];
        var _useState1 = _sliced_to_array((0, _react.useState)(false), 2), hasHiddenFiles = _useState1[0], setHasHiddenFiles = _useState1[1];
        var filesLength = Object.keys(filesInfo).length;
        var horizontalClass = flow === 'horizontal' ? _Attachtokens.classes.horizontal : undefined;
        var verticalClass = flow === 'vertical' ? _Attachtokens.classes.vertical : undefined;
        var autoClass = flow === 'auto' ? _Attachtokens.classes.auto : undefined;
        var withHelperTextClass = helperText ? _Attachtokens.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] = (0, _utils1.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 = _object_spread({}, 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 ? void 0 : cellHelperRefs.current)) {
                cellHelperRefs.current[key] = element;
            }
        };
        var updateHiddenFiles = function updateHiddenFiles() {
            var _window_getComputedStyle_columnGap;
            var newFilesInfo = _object_spread({}, 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_getComputedStyle_columnGap = window.getComputedStyle(fileWrapper).columnGap) !== null && _window_getComputedStyle_columnGap !== void 0 ? _window_getComputedStyle_columnGap : 0, 10);
            var totalWidth = 0;
            var firstHidden = Object.entries(cellHelperRefs.current).findIndex(function(param) {
                var _param = _sliced_to_array(param, 2), _ = _param[0], cell = _param[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);
        };
        (0, _react.useLayoutEffect)(function() {
            updateHiddenFiles();
        }, [
            filesLength,
            flow,
            multiple
        ]);
        (0, _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(param) {
            var children = param.children;
            return /*#__PURE__*/ _react.default.createElement(Root, {
                size: size,
                view: view
            }, children);
        };
        return /*#__PURE__*/ _react.default.createElement(Root, {
            className: (0, _utils.cx)(horizontalClass, verticalClass, autoClass, withHelperTextClass, className),
            style: style,
            size: size,
            view: view,
            helperTextView: helperTextView,
            ref: ref
        }, /*#__PURE__*/ _react.default.createElement(_Attachstyles.StyledHiddenInput, {
            ref: inputRef,
            accept: accept,
            type: "file",
            id: id,
            name: name,
            multiple: multiple,
            onChange: handleChange
        }), (!hideButtonOnAttach || !filesLength) && /*#__PURE__*/ _react.default.createElement(_Attachstyles.StyledAttachButtonWrapper, null, /*#__PURE__*/ _react.default.createElement(_components.AttachButton, _object_spread({
            ref: buttonRef,
            buttonType: buttonType,
            isLoading: isLoading,
            disabled: disabled,
            onClick: handleClick
        }, rest)), helperText && /*#__PURE__*/ _react.default.createElement(_Attachstyles.StyledHelperText, null, helperText)), (hasAttachment || hideButtonOnAttach) && Boolean(filesLength) && Object.values(filesInfo)[0].isVisible && /*#__PURE__*/ _react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/ _react.default.createElement(_Attachstyles.FilesWrapper, {
            className: (0, _utils.cx)(horizontalClass, verticalClass, autoClass),
            applyOverflow: multiple && flow === 'horizontal'
        }, Object.entries(filesInfo).map(function(param) {
            var _param = _sliced_to_array(param, 2), key = _param[0], _param_ = _param[1], extension = _param_.extension, filenameWithoutExtension = _param_.filenameWithoutExtension, cellContentLeft = _param_.cellContentLeft, isVisible = _param_.isVisible;
            if (!isVisible) {
                return;
            }
            return /*#__PURE__*/ _react.default.createElement(_ui.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.createElement(_ui.DropdownUI, _object_spread_props(_object_spread({
            rootWrapper: RootWrapper,
            size: size,
            filesInfo: filesInfo,
            customIcon: customIcon,
            handleClear: handleClear
        }, dropdownOptions), {
            placement: (_ref = dropdownOptions === null || dropdownOptions === void 0 ? void 0 : dropdownOptions.placement) !== null && _ref !== void 0 ? _ref : 'bottom'
        })), multiple && flow === 'horizontal' && /*#__PURE__*/ _react.default.createElement(_components.HiddenWidthHelper, {
            ref: fileWrapperWidthRef,
            hasHiddenFiles: hasHiddenFiles,
            size: size
        }), multiple && flow === 'horizontal' && (hasAttachment || hideButtonOnAttach) && Boolean(filesLength) && /*#__PURE__*/ _react.default.createElement(_Attachstyles.FilesWrapper, {
            ref: fileWrapperHelperRef,
            className: (0, _utils.cx)(horizontalClass, _Attachtokens.classes.horizontalHidden)
        }, Object.entries(filesInfo).map(function(param) {
            var _param = _sliced_to_array(param, 2), key = _param[0], _param_ = _param[1], extension = _param_.extension, filenameWithoutExtension = _param_.filenameWithoutExtension, cellContentLeft = _param_.cellContentLeft;
            return /*#__PURE__*/ _react.default.createElement(_ui.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: _Attachstyles.base,
    variations: {
        view: {
            css: _base1.base
        },
        helperTextView: {
            css: _base2.base
        },
        size: {
            css: _base.base
        }
    },
    defaults: {
        view: 'default',
        helperTextView: 'default',
        size: 'm'
    }
};
