import { jsx as _jsx } from "@emotion/react/jsx-runtime";
import React, { useState, useContext, useMemo, useEffect, } from 'react';
import i18next from 'i18next';
import { schemaRegistry } from '../../../decorators/schema-registry';
import { componentsSchema, systemsSchema } from '../../modules/inspector/widgets';
import { useExtension } from '../../hooks';
import { EngineContext } from '../engine-provider';
import { EventType } from '../../../events';
import { NAMESPACE_EDITOR, NAMESPACE_EXTENSION } from './consts';
export const SchemasContext = React.createContext({
    components: [],
    systems: [],
});
export const SchemasProvider = ({ children, }) => {
    const { world } = useContext(EngineContext);
    const extension = useExtension();
    const [extComponentsSchema, setExtComponentsSchema] = useState(() => schemaRegistry.getGroup('component'));
    const [extSystemsSchema, setExtSystemsSchema] = useState(() => schemaRegistry.getGroup('system'));
    const components = useMemo(() => [].concat(Object.keys(componentsSchema).map((key) => ({
        name: key,
        schema: componentsSchema[key],
        namespace: NAMESPACE_EDITOR,
    })), extComponentsSchema ? Object.keys(extComponentsSchema).map((key) => ({
        name: key,
        schema: extComponentsSchema[key],
        namespace: NAMESPACE_EXTENSION,
    })) : []), [extComponentsSchema]);
    const systems = useMemo(() => [].concat(Object.keys(systemsSchema).map((key) => ({
        name: key,
        schema: systemsSchema[key],
        namespace: NAMESPACE_EDITOR,
    })), extSystemsSchema ? Object.keys(extSystemsSchema).map((key) => ({
        name: key,
        schema: extSystemsSchema[key],
        namespace: NAMESPACE_EXTENSION,
    })) : []), [extSystemsSchema]);
    useMemo(() => {
        Object.keys(extension.locales).forEach((lng) => {
            if (i18next.hasResourceBundle(lng, NAMESPACE_EXTENSION)) {
                i18next.removeResourceBundle(lng, NAMESPACE_EXTENSION);
            }
            i18next.addResourceBundle(lng, NAMESPACE_EXTENSION, extension.locales[lng]);
        });
    }, [extension]);
    useEffect(() => {
        const handleExtensionUpdated = () => {
            setExtComponentsSchema(schemaRegistry.getGroup('component'));
            setExtSystemsSchema(schemaRegistry.getGroup('system'));
        };
        world.addEventListener(EventType.ExtensionUpdated, handleExtensionUpdated);
        return () => {
            world.removeEventListener(EventType.ExtensionUpdated, handleExtensionUpdated);
        };
    }, [world]);
    const context = useMemo(() => ({
        components,
        systems,
    }), [components, systems]);
    return (_jsx(SchemasContext.Provider, { value: context, children: children }));
};
