// packages/block-editor/src/components/inserter/media-tab/hooks.js
import { useEffect, useState, useRef } from "@wordpress/element";
import { useSelect } from "@wordpress/data";
import { store as blockEditorStore } from "../../../store";
import { unlock } from "../../../lock-unlock";
function useMediaResults(category, query = {}) {
  const [mediaList, setMediaList] = useState();
  const [isLoading, setIsLoading] = useState(false);
  const lastRequestRef = useRef();
  useEffect(() => {
    (async () => {
      const key = JSON.stringify({
        category: category.name,
        ...query
      });
      lastRequestRef.current = key;
      setIsLoading(true);
      setMediaList([]);
      const _media = await category.fetch?.(query);
      if (key === lastRequestRef.current) {
        setMediaList(_media);
        setIsLoading(false);
      }
    })();
  }, [category.name, ...Object.values(query)]);
  return { mediaList, isLoading };
}
function useMediaCategories(rootClientId) {
  const [categories, setCategories] = useState([]);
  const inserterMediaCategories = useSelect(
    (select) => unlock(select(blockEditorStore)).getInserterMediaCategories(),
    []
  );
  const { canInsertImage, canInsertVideo, canInsertAudio } = useSelect(
    (select) => {
      const { canInsertBlockType } = select(blockEditorStore);
      return {
        canInsertImage: canInsertBlockType(
          "core/image",
          rootClientId
        ),
        canInsertVideo: canInsertBlockType(
          "core/video",
          rootClientId
        ),
        canInsertAudio: canInsertBlockType(
          "core/audio",
          rootClientId
        )
      };
    },
    [rootClientId]
  );
  useEffect(() => {
    (async () => {
      const _categories = [];
      if (!inserterMediaCategories) {
        return;
      }
      const categoriesHaveMedia = new Map(
        await Promise.all(
          inserterMediaCategories.map(async (category) => {
            if (category.isExternalResource) {
              return [category.name, true];
            }
            let results = [];
            try {
              results = await category.fetch({
                per_page: 1
              });
            } catch (e) {
            }
            return [category.name, !!results.length];
          })
        )
      );
      const canInsertMediaType = {
        image: canInsertImage,
        video: canInsertVideo,
        audio: canInsertAudio
      };
      inserterMediaCategories.forEach((category) => {
        if (canInsertMediaType[category.mediaType] && categoriesHaveMedia.get(category.name)) {
          _categories.push(category);
        }
      });
      if (!!_categories.length) {
        setCategories(_categories);
      }
    })();
  }, [
    canInsertImage,
    canInsertVideo,
    canInsertAudio,
    inserterMediaCategories
  ]);
  return categories;
}
export {
  useMediaCategories,
  useMediaResults
};
//# sourceMappingURL=hooks.js.map
