"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useGallery = void 0;
var _tsSdkReactNative = require("@amityco/ts-sdk-react-native");
var _react = require("react");
var _useAuth = _interopRequireDefault(require("./useAuth"));
var _postType = require("../utils/postType");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
const useGallery = ({
  targetId,
  targetType,
  dataType,
  limit
}) => {
  const {
    apiRegion
  } = (0, _useAuth.default)();
  const onNextPageRef = (0, _react.useRef)(null);
  const [mediaFiles, setMediaFiles] = (0, _react.useState)([]);
  const getFile = (0, _react.useCallback)(fileId => {
    return `https://api.${apiRegion}.amity.co/api/v3/files/${fileId}/download?size=medium`;
  }, [apiRegion]);
  (0, _react.useEffect)(() => {
    const unsubscribe = _tsSdkReactNative.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' && (0, _postType.isImagePost)(mediaData) ? getFile(mediaData.data.fileId) : dataType === 'video' && (0, _postType.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
  };
};
exports.useGallery = useGallery;
//# sourceMappingURL=useGallery.js.map