import { useCallback, useEffect, useState } from "react";
import { useDebouncedCallback } from "use-debounce";
import { getWorkbox } from "../../services/contentService";
import { getItemDescriptor } from "../../utils";
export function useWorkbox(params) {
    const { page, currentItemDescriptor, validate } = params;
    const [workboxItems, setWorkboxItems] = useState([]);
    useEffect(() => {
        if (!workboxItems || workboxItems.length === 0)
            return;
        const itemsToValidate = workboxItems.map((x) => x.item);
        validate(itemsToValidate);
    }, [workboxItems, validate]);
    const loadWorkbox = useCallback(async (items) => {
        if (!items.length) {
            setWorkboxItems([]);
            return;
        }
        const workbox = await getWorkbox(items.map((x) => getItemDescriptor(x)));
        const results = workbox.data || [];
        const sorted = results.sort((a, b) => {
            if (a.isPublished === b.isPublished)
                return ((b.workflowCommands?.length || 0) - (a.workflowCommands?.length || 0));
            return !a.isPublished || !a.isPublishable ? -1 : 1;
        });
        setWorkboxItems(sorted);
    }, []);
    const loadWorkboxDebounced = useDebouncedCallback((items) => {
        loadWorkbox(items);
    }, 500);
    useEffect(() => {
        const items = [];
        if (currentItemDescriptor)
            items.push(currentItemDescriptor);
        if (page)
            collectAllItems(page.rootComponent, items);
        loadWorkboxDebounced(items.filter(Boolean));
        return () => loadWorkboxDebounced.cancel();
    }, [page, currentItemDescriptor, loadWorkboxDebounced]);
    function collectAllItems(component, items) {
        component.placeholders.forEach((x) => {
            x.components.forEach((y) => {
                if (y.isShared && y.datasourceItem) {
                    items.push(y.datasourceItem);
                }
                collectAllItems(y, items);
            });
        });
    }
    return { workboxItems };
}
//# sourceMappingURL=useWorkbox.js.map