"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useLiveCollection = useLiveCollection;
var _react = require("react");
function useLiveCollection({
  fetcher,
  params,
  callback = () => {},
  enabled = true
}) {
  const [loadMoreHasBeenCalled, setLoadMoreHasBeenCalled] = (0, _react.useState)(false);
  const loadingCountRef = (0, _react.useRef)(0);
  const [isLoadingFirstPage, setIsLoadingFirstPage] = (0, _react.useState)(false);
  const [isLoading, setIsLoading] = (0, _react.useState)(false);
  const [items, setItems] = (0, _react.useState)([]);
  const [error, setError] = (0, _react.useState)(null);
  const [hasMore, setHasMore] = (0, _react.useState)(false);
  const loadMoreFnRef = (0, _react.useRef)(null);
  const unsubscribeRef = (0, _react.useRef)(null);
  const loadMore = (0, _react.useCallback)(() => {
    if (loadMoreFnRef.current) {
      var _loadMoreFnRef$curren;
      setLoadMoreHasBeenCalled(true);
      (_loadMoreFnRef$curren = loadMoreFnRef.current) === null || _loadMoreFnRef$curren === void 0 || _loadMoreFnRef$curren.call(loadMoreFnRef);
    }
  }, [loadMoreFnRef]);
  const callbackFn = (0, _react.useCallback)(response => {
    if (!enabled) return;
    if (response.data) setItems(response.data);
    if (loadingCountRef.current === 0) {
      setIsLoadingFirstPage(response.loading);
    } else {
      setIsLoadingFirstPage(false);
      setIsLoading(response.loading);
    }
    loadingCountRef.current += 1;
    setHasMore(response.hasNextPage);
    setError(response.error);
    loadMoreFnRef.current = response.onNextPage;
    callback(response);
  }, [enabled]);
  (0, _react.useEffect)(() => {
    if (!enabled) return undefined;
    const {
      unsubscribe
    } = subscribe({
      fetcher,
      params,
      callback: callbackFn
    });
    unsubscribeRef.current = unsubscribe;
    return () => unsubscribe();
  }, [JSON.stringify(params), enabled]);
  const refresh = (0, _react.useCallback)(() => {
    if (unsubscribeRef.current) unsubscribeRef.current();
    const {
      unsubscribe
    } = subscribe({
      fetcher,
      params,
      callback: callbackFn
    });
    unsubscribeRef.current = unsubscribe;
    return () => unsubscribe();
  }, [fetcher, JSON.stringify(params)]);
  return {
    error,
    items,
    hasMore,
    isLoading,
    loadMore,
    refresh,
    isLoadingFirstPage,
    loadMoreHasBeenCalled
  };
}
const subscribe = ({
  fetcher,
  params,
  callback,
  config
}) => {
  // Check if fetcher accepts params (has 2-3 arguments) or only callback (has 1-2 arguments)
  const unsubscribe = params !== undefined ? fetcher(params, response => callback(response), config) : fetcher(response => callback(response), config);
  return {
    unsubscribe
  };
};
//# sourceMappingURL=useLiveCollection.js.map