import { jsx } from "react/jsx-runtime";
import { createContext, useMemo } from "react";
import { uid, useFieldSchema } from "@tachybase/schema";
import { useAPIClient, useRequest } from "../api-client/index.mjs";
import { Plugin } from "../application/Plugin.mjs";
import { BlockTemplate } from "./BlockTemplate.mjs";
import { useSchemaTemplateManager } from "./useSchemaTemplateManager.mjs";
const SchemaTemplateManagerContext = /*#__PURE__*/ createContext({});
SchemaTemplateManagerContext.displayName = 'SchemaTemplateManagerContext';
const SchemaTemplateManagerProvider = (props)=>{
    const { templates, refresh } = props;
    return /*#__PURE__*/ jsx(SchemaTemplateManagerContext.Provider, {
        value: {
            templates,
            refresh
        },
        children: props.children
    });
};
const regenerateUid = (s)=>{
    s['name'] = s['x-uid'] = uid();
    Object.keys(s.properties || {}).forEach((key)=>{
        regenerateUid(s.properties[key]);
    });
};
const useSchemaTemplate = ()=>{
    const { getTemplateBySchema } = useSchemaTemplateManager();
    const fieldSchema = useFieldSchema();
    const schemaId = fieldSchema['x-uid'];
    const templateKey = fieldSchema['x-template-key'];
    const result = useMemo(()=>getTemplateBySchema(fieldSchema), [
        schemaId,
        templateKey
    ]);
    return result;
};
const InternalRemoteSchemaTemplateManagerProvider = (props)=>{
    var _service_data;
    const api = useAPIClient();
    const options = {
        resource: 'uiSchemaTemplates',
        action: 'list',
        params: {
            paginate: false
        }
    };
    const service = useRequest(options);
    if (service.loading && !service.data) return;
    return /*#__PURE__*/ jsx(SchemaTemplateManagerProvider, {
        refresh: async ()=>{
            const { data } = await api.request(options);
            service.mutate(data);
        },
        templates: null == service ? void 0 : null == (_service_data = service.data) ? void 0 : _service_data.data,
        children: props.children
    });
};
const RemoteSchemaTemplateManagerProvider = (props)=>/*#__PURE__*/ jsx(InternalRemoteSchemaTemplateManagerProvider, {
        children: props.children
    });
class RemoteSchemaTemplateManagerPlugin extends Plugin {
    async load() {
        this.addComponents();
        this.app.addProviders([
            RemoteSchemaTemplateManagerProvider
        ]);
    }
    addComponents() {
        this.app.addComponents({
            BlockTemplate: BlockTemplate
        });
    }
}
export { RemoteSchemaTemplateManagerPlugin, RemoteSchemaTemplateManagerProvider, SchemaTemplateManagerContext, SchemaTemplateManagerProvider, regenerateUid, useSchemaTemplate };
