"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _tsSdkReactNative = require("@amityco/ts-sdk-react-native");
var _react = require("react");
const useSearch = (searchText = '', privateCommunityId = '') => {
  const onNextPageRef = (0, _react.useRef)(null);
  const [searchResult, setSearchResult] = (0, _react.useState)([]);
  const searchPrivateCommunityMember = (0, _react.useCallback)(text => {
    return _tsSdkReactNative.CommunityRepository.Membership.searchMembers({
      communityId: privateCommunityId,
      search: text,
      limit: 5,
      sortBy: 'firstCreated',
      memberships: ['member'],
      includeDeleted: false
    }, ({
      data,
      error,
      hasNextPage,
      onNextPage
    }) => {
      if (error) return null;
      onNextPageRef.current = hasNextPage ? onNextPage : null;
      const mappedSearchData = data.map(item => {
        return {
          ...item.user,
          name: item.user.displayName,
          id: item.userId
        };
      });
      setSearchResult(mappedSearchData);
    });
  }, [privateCommunityId]);
  const searchAllUsers = (0, _react.useCallback)(text => {
    return _tsSdkReactNative.UserRepository.searchUserByDisplayName({
      displayName: text,
      limit: 5,
      searchBy: [_tsSdkReactNative.SearchUsersByEnum.DISPLAY_NAME],
      matchType: _tsSdkReactNative.UserRepository.AmityUserSearchMatchType.PARTIAL
    }, ({
      data,
      error,
      hasNextPage,
      onNextPage
    }) => {
      if (error) return null;
      hasNextPage ? onNextPageRef.current = onNextPage : onNextPageRef.current = null;
      const mappedSearchData = data.map(item => {
        return {
          ...item,
          name: item.displayName,
          id: item.userId
        };
      });
      setSearchResult(mappedSearchData);
    });
  }, []);
  (0, _react.useEffect)(() => {
    if (privateCommunityId) return searchPrivateCommunityMember(searchText);
    if (searchText.length < 2) return setSearchResult([]);
    return searchAllUsers(searchText);
  }, [privateCommunityId, searchAllUsers, searchPrivateCommunityMember, searchText]);
  return {
    searchResult,
    getNextPage: onNextPageRef.current
  };
};
var _default = exports.default = useSearch;
//# sourceMappingURL=useSearch.js.map