"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 dropzoneConfig () {
        return dropzoneConfig;
    },
    get dropzoneRoot () {
        return dropzoneRoot;
    }
});
const _react = /*#__PURE__*/ _interop_require_wildcard(require("react"));
const _utils = require("../../utils");
const _hooks = require("../../hooks");
const _Icon = require("../_Icon");
const _base = require("./variations/_view/base");
const _base1 = require("./variations/_size/base");
const _base2 = require("./variations/_disabled/base");
const _Dropzonestyles = require("./Dropzone.styles");
const _Dropzonetokens = require("./Dropzone.tokens");
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;
}
const dropzoneRoot = (Root)=>/*#__PURE__*/ (0, _react.forwardRef)(({ files, className, style, accept, multiple, title, description, icon, iconPlacement = 'left', size, view, disabled, stretch, width, height, onDragEnter, onDragLeave, onDragOver, onDrop, validator, onClick, onChange, onChoseFiles, ...rest }, outerRef)=>{
        const [isDropzoneActive, setIsDropzoneActive] = (0, _react.useState)(false);
        const [innerTitle, setInnerTitle] = (0, _react.useState)(title);
        const [innerDescription, setInnerDescription] = (0, _react.useState)(description);
        const [innerFiles, setInnerFiles] = (0, _react.useState)([]);
        const currentFiles = files !== undefined ? files : innerFiles;
        const inputRef = (0, _react.useRef)(null);
        const forkInputRef = (0, _hooks.useForkRef)(outerRef, inputRef);
        const contentRef = (0, _react.useRef)(null);
        const iconWrapperRef = (0, _react.useRef)(null);
        const iconRef = (0, _react.useRef)(null);
        const contentWrapperRef = (0, _react.useRef)(null);
        const titleRef = (0, _react.useRef)(null);
        const titleHelperRef = (0, _react.useRef)(null);
        const descriptionRef = (0, _react.useRef)(null);
        const descriptionHelperRef = (0, _react.useRef)(null);
        const innerWidth = width ? (0, _utils.getSizeValueFromProp)(width) : 'fit-content';
        const innerHeight = height ? (0, _utils.getSizeValueFromProp)(height) : 'fit-content';
        const isTitleString = typeof title === 'string';
        const isDescriptionString = typeof description === 'string';
        const processFiles = async (rawFiles, callback, afterAction)=>{
            if (!rawFiles?.length) {
                return;
            }
            const files = [
                ...rawFiles
            ];
            let res = {
                acceptedFiles: files
            };
            if (validator) {
                res = await validator?.(files);
            }
            if (callback) {
                await callback(res);
            }
            if (afterAction) {
                afterAction();
            }
        };
        const handleDragEnter = (event)=>{
            if (disabled) {
                return;
            }
            event.preventDefault();
            event.stopPropagation();
            if (onDragEnter) {
                onDragEnter(event);
            }
            setIsDropzoneActive(true);
        };
        const handleDragLeave = (event)=>{
            if (disabled) {
                return;
            }
            event.preventDefault();
            if (onDragLeave) {
                onDragLeave(event);
            }
            setIsDropzoneActive(false);
        };
        const handleDragOver = (event)=>{
            if (disabled) {
                return;
            }
            event.preventDefault();
            if (onDragOver) {
                onDragOver(event);
            }
            const { files: rawFiles } = event.dataTransfer;
            if (!isDropzoneActive && rawFiles && rawFiles.length > 0) {
                setIsDropzoneActive(true);
            }
        };
        const handleDrop = async (event)=>{
            if (disabled) {
                return;
            }
            event.preventDefault();
            event.persist();
            const { files: rawFiles } = event.dataTransfer;
            const afterAction = ()=>{
                event.dataTransfer.clearData();
                setIsDropzoneActive(false);
            };
            await processFiles(rawFiles, onDrop, afterAction);
        };
        const handleClick = (event)=>{
            if (!inputRef.current || disabled) {
                return;
            }
            inputRef.current.click();
            if (onClick) {
                onClick(event);
            }
        };
        const handleChange = async (event)=>{
            if (disabled) {
                return;
            }
            if (onChange) {
                onChange(event);
            }
            const { files: rawFiles } = event.target;
            await processFiles(rawFiles, async (res)=>{
                setInnerFiles(res.acceptedFiles);
                if (onChoseFiles) {
                    await onChoseFiles(res);
                }
            });
        };
        const truncateContent = ()=>{
            if (!_utils.canUseDOM || !descriptionRef?.current || !contentWrapperRef?.current || !titleRef?.current || !titleHelperRef?.current || !iconRef?.current || !iconWrapperRef?.current || !contentRef?.current || !descriptionHelperRef?.current || !width && !height) {
                return;
            }
            const contentHeight = contentRef.current.offsetHeight;
            const iconHeight = iconRef.current.offsetHeight;
            const iconWidth = iconPlacement === 'top' ? 0 : iconRef.current.offsetWidth;
            const titleHeight = titleRef.current.offsetHeight;
            const iconContentGap = iconPlacement === 'top' ? Number(window.getComputedStyle(iconWrapperRef.current).rowGap.replace('px', '')) : 0;
            const availableWidth = contentRef.current.offsetWidth - iconWidth - iconContentGap;
            const contentGap = Number(window.getComputedStyle(contentWrapperRef.current).rowGap.replace('px', ''));
            const titleFontWidth = Math.floor(titleHelperRef.current.offsetWidth);
            const titleFontHeight = Math.floor(titleHelperRef.current.offsetHeight);
            const descriptionFontWidth = Math.floor(descriptionHelperRef.current.offsetWidth);
            const descriptionFontHeight = Math.floor(descriptionHelperRef.current.offsetHeight);
            const titleAvailableHeight = contentHeight - iconHeight - iconContentGap - descriptionFontHeight - contentGap;
            const titleMaxChars = Math.floor(availableWidth / titleFontWidth * (titleAvailableHeight / titleFontHeight));
            let resTitleLength = 0;
            if (title && isTitleString) {
                const newTitle = title.length <= titleMaxChars ? title : `${title.slice(0, titleMaxChars - 3)}...`;
                resTitleLength = newTitle.length;
                setInnerTitle(newTitle);
            }
            const resultTitleHeight = Math.floor(titleFontHeight * titleFontWidth * resTitleLength / availableWidth);
            const descriptionAvailableHeight = titleAvailableHeight >= titleHeight + 2 * descriptionFontHeight ? contentHeight - resultTitleHeight - iconContentGap - contentGap : descriptionFontHeight;
            const descriptionMaxChars = Math.floor(availableWidth / descriptionFontWidth * (descriptionAvailableHeight / descriptionFontHeight));
            if (description && isDescriptionString) {
                const newDescription = description.length <= descriptionMaxChars ? description : `${description.slice(0, descriptionMaxChars - 3)}...`;
                setInnerDescription(newDescription);
            }
        };
        (0, _hooks.useResizeObserver)(contentRef, truncateContent);
        (0, _react.useEffect)(()=>{
            truncateContent();
        }, [
            title,
            description,
            iconPlacement
        ]);
        (0, _react.useEffect)(()=>{
            if (inputRef.current) {
                inputRef.current.value = '';
            }
        }, [
            currentFiles
        ]);
        return /*#__PURE__*/ _react.default.createElement(Root, {
            className: (0, _utils.cx)(className, isDropzoneActive && _Dropzonetokens.classes.active, stretch && _Dropzonetokens.classes.stretch, disabled && _Dropzonetokens.classes.disabled),
            view: view,
            size: size,
            disabled: disabled,
            tabIndex: 0,
            style: {
                ...style,
                [_Dropzonetokens.privateTokens.width]: innerWidth,
                [_Dropzonetokens.privateTokens.height]: innerHeight
            }
        }, /*#__PURE__*/ _react.default.createElement(_Dropzonestyles.DropzoneHandlerOverlay, {
            onDragEnter: handleDragEnter,
            onDragLeave: handleDragLeave,
            onDragOver: handleDragOver,
            onDrop: handleDrop,
            onClick: handleClick
        }), /*#__PURE__*/ _react.default.createElement(_Dropzonestyles.Content, {
            ref: contentRef
        }, /*#__PURE__*/ _react.default.createElement(_Dropzonestyles.IconWrapper, {
            ref: iconWrapperRef,
            className: (0, _utils.cx)(iconPlacement === 'top' && _Dropzonetokens.classes.verticalContentPlacing)
        }, /*#__PURE__*/ _react.default.createElement(_Dropzonestyles.StyledIcon, {
            ref: iconRef
        }, icon || /*#__PURE__*/ _react.default.createElement(_Icon.IconArrowBarDown, {
            color: "inherit",
            size: "s"
        })), /*#__PURE__*/ _react.default.createElement(_Dropzonestyles.ContentWrapper, {
            ref: contentWrapperRef
        }, title && isTitleString ? /*#__PURE__*/ _react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/ _react.default.createElement(_Dropzonestyles.Title, {
            ref: titleRef
        }, innerTitle), /*#__PURE__*/ _react.default.createElement(_Dropzonestyles.TitleHelper, {
            ref: titleHelperRef
        }, "C")) : title, description && isDescriptionString ? /*#__PURE__*/ _react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/ _react.default.createElement(_Dropzonestyles.Description, {
            ref: descriptionRef
        }, innerDescription), /*#__PURE__*/ _react.default.createElement(_Dropzonestyles.DescriptionHelper, {
            ref: descriptionHelperRef
        }, "C")) : description))), /*#__PURE__*/ _react.default.createElement(_Dropzonestyles.HiddenInput, {
            ref: forkInputRef,
            type: "file",
            accept: accept,
            multiple: multiple,
            tabIndex: -1,
            onChange: handleChange,
            ...rest
        }));
    });
const dropzoneConfig = {
    name: 'Dropzone',
    tag: 'div',
    layout: dropzoneRoot,
    base: _Dropzonestyles.base,
    variations: {
        view: {
            css: _base.base
        },
        size: {
            css: _base1.base
        },
        disabled: {
            css: _base2.base,
            attrs: true
        }
    },
    defaults: {
        view: 'default',
        size: 'm'
    }
};
