import { jsx as _jsx } from "@emotion/react/jsx-runtime";
import React, { useState, useMemo, useEffect, useContext } from 'react';
import { Engine, MouseInputSystem, MouseControlSystem, CameraSystem, UIBridge, Renderer, Transform, Camera, MouseControl, Shape, Sprite, BitmapText, PixiView, Mesh, } from 'dacha';
import { CommandContext } from '../command-provider';
import { getEditorConfig } from '../../../engine/config';
import { ProjectLoader, SceneViewer, ToolManager, ZoomToolSystem, HandToolSystem, PointerToolSystem, TemplateToolSystem, GridSystem, SettingsSystem, DebugVisualizer, Tool, ToolController, Settings, Frame, Technical, } from '../../../engine';
export const EngineContext = React.createContext({});
export const EngineProvider = ({ children, }) => {
    const { store } = useContext(CommandContext);
    const [context, setContext] = useState();
    const sorting = useMemo(() => {
        var _a, _b, _c, _d;
        const projectConfig = window.electron.getProjectConfig();
        const projectSorting = projectConfig.globalOptions.find((option) => option.name === 'sorting');
        return {
            order: ((_b = (_a = projectSorting === null || projectSorting === void 0 ? void 0 : projectSorting.options) === null || _a === void 0 ? void 0 : _a.order) !== null && _b !== void 0 ? _b : 'bottomRight'),
            layers: ((_d = (_c = projectSorting === null || projectSorting === void 0 ? void 0 : projectSorting.options) === null || _c === void 0 ? void 0 : _c.layers) !== null && _d !== void 0 ? _d : []),
        };
    }, []);
    const editorEngine = useMemo(() => new Engine({
        config: getEditorConfig({ sorting, store }),
        systems: [
            MouseInputSystem,
            MouseControlSystem,
            CameraSystem,
            UIBridge,
            Renderer,
            ProjectLoader,
            SceneViewer,
            ToolManager,
            ZoomToolSystem,
            HandToolSystem,
            PointerToolSystem,
            TemplateToolSystem,
            GridSystem,
            SettingsSystem,
            DebugVisualizer,
        ],
        components: [
            Transform,
            Camera,
            MouseControl,
            Tool,
            ToolController,
            Shape,
            Sprite,
            BitmapText,
            Mesh,
            PixiView,
            Settings,
            Frame,
            Technical,
        ],
        resources: {
            [ProjectLoader.systemName]: {
                store,
            },
            [UIBridge.systemName]: {
                loadUI: () => Promise.resolve({
                    onInit: (options) => setContext(options),
                    onDestroy: () => setContext(void 0),
                }),
            },
        },
    }), [sorting]);
    useEffect(() => {
        void editorEngine.play();
    }, [editorEngine]);
    return (_jsx(EngineContext.Provider, { value: context, children: children }));
};
