"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useAutoSave = void 0;
const react_1 = require("react");
const DEFAULT_AUTOSAVE = {
    enabled: true,
    delay: 500,
};
/**
 * autosave functionality for extensions with edit block
 */
const useAutoSave = ({ autoSave, initialValue, onClose, onSave, }) => {
    const { enabled: autoSaveEnabled, delay: autoSaveDelay } = autoSave ?? DEFAULT_AUTOSAVE;
    const isAutoSaveEnabled = Boolean(autoSaveEnabled);
    const [value, setValue] = (0, react_1.useState)(initialValue || '');
    const [hasUnsavedChanges, setHasUnsavedChanges] = (0, react_1.useState)(false);
    const autoSaveTimeoutRef = (0, react_1.useRef)();
    const handleClearTimeout = () => {
        if (autoSaveTimeoutRef.current) {
            clearTimeout(autoSaveTimeoutRef.current);
        }
    };
    const handleChange = (newValue) => {
        setValue(newValue);
        const hasChanges = newValue !== initialValue;
        setHasUnsavedChanges(hasChanges);
        if (isAutoSaveEnabled && hasChanges) {
            handleClearTimeout();
            const delay = autoSaveDelay ?? DEFAULT_AUTOSAVE.delay;
            autoSaveTimeoutRef.current = setTimeout(() => {
                onSave(newValue);
                setHasUnsavedChanges(false);
            }, delay);
        }
    };
    const handleManualSave = () => {
        handleClearTimeout();
        onSave(value);
        onClose();
    };
    // сleanup timeout on unmount
    (0, react_1.useEffect)(() => {
        return () => {
            handleClearTimeout();
        };
    }, []);
    const isSaveDisabled = isAutoSaveEnabled && !hasUnsavedChanges;
    return {
        value,
        hasUnsavedChanges,
        handleChange,
        handleManualSave,
        handleClearTimeout,
        isAutoSaveEnabled,
        isSaveDisabled,
    };
};
exports.useAutoSave = useAutoSave;
//# sourceMappingURL=useAutoSave.js.map
