"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useCategories = void 0;
var _react = require("react");
var _tsSdkReactNative = require("@amityco/ts-sdk-react-native");
var _useAuth = _interopRequireDefault(require("../../core/hooks/useAuth"));
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
const useCategories = ({
  limit = 5
} = {}) => {
  const {
    isConnected
  } = (0, _useAuth.default)();
  const [categories, setCategories] = (0, _react.useState)();
  const [loading, setLoading] = (0, _react.useState)(true);
  const [hasMore, setHasMore] = (0, _react.useState)(false);
  const [error, setError] = (0, _react.useState)(null);
  const [onNextCategoryPage, setOnNextCategoryPage] = (0, _react.useState)(null);
  const unsubscribersRef = (0, _react.useRef)([]);
  const fetchCategories = () => {
    setLoading(true);
    return _tsSdkReactNative.CategoryRepository.getCategories({
      limit
    }, ({
      error,
      loading,
      data,
      hasNextPage,
      onNextPage
    }) => {
      if (error) setError(error);
      if (!loading) {
        setLoading(loading);
        setCategories(data);
        setHasMore(hasNextPage);
        setOnNextCategoryPage(() => {
          if (hasNextPage) return onNextPage;
          return null;
        });
      }
    });
  };
  const unsubscribeListener = () => {
    unsubscribersRef.current.forEach(unsubscriber => unsubscriber());
    unsubscribersRef.current = [];
  };
  const refresh = () => {
    unsubscribeListener();
    setError(null);
    const unsubscribe = fetchCategories();
    unsubscribersRef.current.push(unsubscribe);
  };
  (0, _react.useEffect)(() => {
    if (!isConnected) return () => {};
    const unsubscribe = fetchCategories();
    unsubscribersRef.current.push(unsubscribe);
    return () => unsubscribeListener();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isConnected]);
  return {
    refresh,
    categories,
    hasMore,
    onNextCategoryPage,
    loading,
    error
  };
};
exports.useCategories = useCategories;
//# sourceMappingURL=useCategories.js.map