import { jsx as _jsx } from "@emotion/react/jsx-runtime";
import React, { useEffect, useMemo, useState, } from 'react';
import { CommanderStore } from '../../../store';
import { ROOT_SCOPE } from '../../../consts/scopes';
export const CommandContext = React.createContext({});
export const CommandProvider = ({ children, }) => {
    const store = useMemo(() => {
        const projectConfig = window.electron.getProjectConfig();
        return new CommanderStore(projectConfig);
    }, []);
    const [activeScope, setActiveScope] = useState(ROOT_SCOPE);
    useEffect(() => {
        const handleOperation = (operation) => () => {
            const { activeElement } = document;
            if ((activeElement === null || activeElement === void 0 ? void 0 : activeElement.tagName) === 'INPUT' || (activeElement === null || activeElement === void 0 ? void 0 : activeElement.tagName) === 'TEXTAREA') {
                document.execCommand(operation);
                return;
            }
            store[operation]({ scope: activeScope });
        };
        const undoUnsubscribe = window.electron.onUndo(handleOperation('undo'));
        const redoUnsubscribe = window.electron.onRedo(handleOperation('redo'));
        return () => {
            undoUnsubscribe();
            redoUnsubscribe();
        };
    }, [activeScope]);
    const currentContext = useMemo(() => ({
        store,
        activeScope,
        setActiveScope,
    }), [activeScope]);
    return (_jsx(CommandContext.Provider, { value: currentContext, children: children }));
};
