"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useRecommendedCommunities = 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 useRecommendedCommunities = options => {
  const {
    limit = 4
  } = options || {};
  const {
    isConnected
  } = (0, _useAuth.default)();
  const [communities, setCommunities] = (0, _react.useState)();
  const [loading, setLoading] = (0, _react.useState)(true);
  const [error, setError] = (0, _react.useState)(null);
  const unsubscribersRef = (0, _react.useRef)([]);
  const fetchRecommendedCommunities = () => {
    setLoading(true);
    return _tsSdkReactNative.CommunityRepository.getRecommendedCommunities({
      limit: 100
    }, ({
      error,
      loading,
      data
    }) => {
      setLoading(loading);
      if (error) setError(error);
      if (!loading) {
        setCommunities(data.filter(community => !community.isJoined));
      }
    });
  };
  const unsubscribeListener = () => {
    unsubscribersRef.current.forEach(unsubscriber => unsubscriber());
    unsubscribersRef.current = [];
  };
  const refresh = () => {
    unsubscribeListener();
    setError(null);
    const unsubscribe = fetchRecommendedCommunities();
    unsubscribersRef.current.push(unsubscribe);
  };
  const onJoinCommunity = communityId => {
    setCommunities(prev => [...(prev === null || prev === void 0 ? void 0 : prev.filter(community => {
      if (community.communityId === communityId) {
        return {
          ...community,
          isJoined: true
        };
      }
      return community;
    }))]);
  };
  (0, _react.useEffect)(() => {
    if (!isConnected) return () => {};
    const unsubscribe = fetchRecommendedCommunities();
    unsubscribersRef.current.push(unsubscribe);
    return () => unsubscribeListener();
  }, [isConnected]);
  return {
    refresh,
    onJoinCommunity,
    communities: communities === null || communities === void 0 ? void 0 : communities.slice(0, limit),
    loading,
    error
  };
};
exports.useRecommendedCommunities = useRecommendedCommunities;
//# sourceMappingURL=useRecommenedCommunities.js.map