import { jsx } from "react/jsx-runtime";
import { createContext, useCallback, useContext, useEffect, useMemo, useState } from "react";
import { AutopilotChatEvent } from "../service/index.js";
import { useChatService } from "./chat-service.provider.js";
const EMPTY_RESULT = {
    items: [],
    done: true
};
const ResourceDataContext = /*#__PURE__*/ createContext({
    topLevelResources: [],
    hasResources: false,
    paginatedResources: false,
    getNestedResources: async ()=>EMPTY_RESULT,
    globalSearch: async ()=>EMPTY_RESULT,
    onResourceSelected: ()=>{}
});
function AutopilotResourceDataProvider({ children }) {
    const chatService = useChatService();
    const [resourceManager, setResourceManager] = useState();
    const [topLevelResources, setTopLevelResources] = useState([]);
    const paginatedResources = chatService?.getConfig?.()?.paginatedResources ?? false;
    useEffect(()=>{
        if (!chatService) return;
        const unsubscribeResourceManager = chatService.on(AutopilotChatEvent.SetResourceManager, (manager)=>{
            setResourceManager(manager);
            setTopLevelResources(manager?.getTopLevelResources() ?? []);
        });
        const existingManager = chatService.getResourceManager?.();
        if (existingManager) {
            setResourceManager(existingManager);
            setTopLevelResources(existingManager.getTopLevelResources());
        }
        return ()=>unsubscribeResourceManager();
    }, [
        chatService
    ]);
    const hasResources = topLevelResources.length > 0;
    const getNestedResources = useCallback(async (resourceId, options)=>{
        if (!resourceManager) return EMPTY_RESULT;
        return resourceManager.getNestedResources(resourceId, options);
    }, [
        resourceManager
    ]);
    const globalSearch = useCallback(async (options)=>{
        if (!resourceManager) return EMPTY_RESULT;
        return resourceManager.globalSearch(options);
    }, [
        resourceManager
    ]);
    const onResourceSelected = useCallback((item)=>{
        resourceManager?.onResourceSelected?.(item);
    }, [
        resourceManager
    ]);
    const contextValue = useMemo(()=>({
            topLevelResources,
            hasResources,
            paginatedResources,
            getNestedResources,
            globalSearch,
            onResourceSelected
        }), [
        topLevelResources,
        hasResources,
        paginatedResources,
        getNestedResources,
        globalSearch,
        onResourceSelected
    ]);
    return /*#__PURE__*/ jsx(ResourceDataContext.Provider, {
        value: contextValue,
        children: children
    });
}
const useResourceData = ()=>useContext(ResourceDataContext);
export { AutopilotResourceDataProvider, useResourceData };
