import { PostRepository } from '@amityco/ts-sdk-react-native';
import { useCallback, useEffect, useState, useRef } from 'react';
import useAuth from './useAuth';
import { isImagePost, isVideoPost } from '../utils/postType';
export const useGallery = ({
  targetId,
  targetType,
  dataType,
  limit
}) => {
  const {
    apiRegion
  } = useAuth();
  const onNextPageRef = useRef(null);
  const [mediaFiles, setMediaFiles] = useState([]);
  const getFile = useCallback(fileId => {
    return `https://api.${apiRegion}.amity.co/api/v3/files/${fileId}/download?size=medium`;
  }, [apiRegion]);
  useEffect(() => {
    const unsubscribe = PostRepository.getPosts({
      targetId: targetId,
      targetType,
      dataTypes: [dataType],
      limit
    }, async ({
      data,
      error,
      onNextPage,
      hasNextPage,
      loading
    }) => {
      if (error) return null;
      if (!loading) {
        onNextPageRef.current = hasNextPage ? onNextPage : null;
        const mappedMediaFiles = data.map(mediaData => {
          const uri = dataType === 'image' && isImagePost(mediaData) ? getFile(mediaData.data.fileId) : dataType === 'video' && isVideoPost(mediaData) ? getFile(mediaData.data.thumbnailFileId) : null;
          return {
            dataType,
            ...mediaData.data,
            uri
          };
        });
        setMediaFiles(mappedMediaFiles);
      }
    });
    return () => unsubscribe();
  }, [dataType, getFile, limit, targetId, targetType]);
  return {
    mediaFiles,
    getNextPage: onNextPageRef.current
  };
};
//# sourceMappingURL=useGallery.js.map