import { parseEntityRef, stringifyEntityRef } from '@backstage/catalog-model';
import { useApi } from '@backstage/core-plugin-api';
import { compact, isEqual } from 'lodash';
import { useRef, useMemo } from 'react';
import useAsync from 'react-use/esm/useAsync';
import { catalogApiRef } from '../../api.esm.js';
import { EntityUserFilter } from '../../filters.esm.js';
import '../../hooks/useEntity.esm.js';
import { useEntityList } from '../../hooks/useEntityListProvider.esm.js';
import 'lodash/isEqual';
import 'lodash/sortBy';
import { useStarredEntities } from '../../hooks/useStarredEntities.esm.js';
import '../../apis/EntityPresentationApi/EntityPresentationApi.esm.js';
import 'lodash/get';
import '../../apis/StarredEntitiesApi/StarredEntitiesApi.esm.js';
import 'zen-observable';
import { reduceCatalogFilters } from '../../utils/filters.esm.js';

function useStarredEntitiesCount() {
  const catalogApi = useApi(catalogApiRef);
  const { filters } = useEntityList();
  const { starredEntities } = useStarredEntities();
  const prevRequest = useRef();
  const request = useMemo(() => {
    const { user, ...allFilters } = filters;
    const compacted = compact(Object.values(allFilters));
    const { orderFields, ...catalogFilters } = reduceCatalogFilters(compacted);
    const facet = "metadata.name";
    const newRequest = {
      ...catalogFilters,
      filter: {
        ...catalogFilters.filter,
        /**
         * here we are filtering entities by `name`. Given this filter,
         * the response might contain more entities than expected, in case multiple entities
         * of different kind or namespace share the same name. Those extra entities are filtered out
         * client side by `EntityUserFilter`, so they won't be visible to the user.
         */
        [facet]: Array.from(starredEntities).map((e) => parseEntityRef(e).name)
      },
      /**
       * limit is set to a high value as we are not expecting many starred entities
       */
      limit: 1e3
    };
    if (isEqual(newRequest, prevRequest.current)) {
      return prevRequest.current;
    }
    prevRequest.current = newRequest;
    return newRequest;
  }, [filters, starredEntities]);
  const { value: count, loading } = useAsync(async () => {
    if (!starredEntities.size) {
      return 0;
    }
    const response = await catalogApi.queryEntities(request);
    return response.items.map(
      (e) => stringifyEntityRef({
        kind: e.kind,
        namespace: e.metadata.namespace,
        name: e.metadata.name
      })
    ).filter((e) => starredEntities.has(e)).length;
  }, [request, starredEntities]);
  const filter = useMemo(
    () => EntityUserFilter.starred(Array.from(starredEntities)),
    [starredEntities]
  );
  return { count, loading, filter };
}

export { useStarredEntitiesCount };
//# sourceMappingURL=useStarredEntitiesCount.esm.js.map
