import { CommunityRepository, SearchUsersByEnum, UserRepository } from '@amityco/ts-sdk-react-native';
import { useCallback, useEffect, useState, useRef } from 'react';
const useSearch = (searchText = '', privateCommunityId = '') => {
  const onNextPageRef = useRef(null);
  const [searchResult, setSearchResult] = useState([]);
  const searchPrivateCommunityMember = useCallback(text => {
    return 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 = useCallback(text => {
    return UserRepository.searchUserByDisplayName({
      displayName: text,
      limit: 5,
      searchBy: [SearchUsersByEnum.DISPLAY_NAME],
      matchType: 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);
    });
  }, []);
  useEffect(() => {
    if (privateCommunityId) return searchPrivateCommunityMember(searchText);
    if (searchText.length < 2) return setSearchResult([]);
    return searchAllUsers(searchText);
  }, [privateCommunityId, searchAllUsers, searchPrivateCommunityMember, searchText]);
  return {
    searchResult,
    getNextPage: onNextPageRef.current
  };
};
export default useSearch;
//# sourceMappingURL=useSearch.js.map