"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useStory = void 0;
var _tsSdkReactNative = require("@amityco/ts-sdk-react-native");
var _react = require("react");
var _reactNative = require("react-native");
const useStory = () => {
  const onNextPageRef = (0, _react.useRef)(null);
  const [fetching, setFetching] = (0, _react.useState)(false);
  const [stories, setStories] = (0, _react.useState)([]);
  const [storyTarget, setStoryTarget] = (0, _react.useState)(null);
  const getStories = (0, _react.useCallback)(param => {
    const unsubscribe = _tsSdkReactNative.StoryRepository.getActiveStoriesByTarget(param, ({
      data,
      error,
      loading,
      hasNextPage,
      onNextPage
    }) => {
      if (error) return;
      setFetching(loading);
      if (!loading) {
        setStories(data);
        const unsubTopic = (0, _tsSdkReactNative.getCommunityStoriesTopic)({
          targetId: param.targetId,
          targetType: param.targetType
        });
        (0, _tsSdkReactNative.subscribeTopic)(unsubTopic);
        onNextPageRef.current = hasNextPage ? onNextPage : null;
      }
    });
    return () => unsubscribe();
  }, []);
  const getStoryTarget = (0, _react.useCallback)(param => {
    const unsubscribe = _tsSdkReactNative.StoryRepository.getTargetById(param, ({
      data,
      error,
      loading
    }) => {
      if (error) return;
      setFetching(loading);
      if (!loading) {
        setStoryTarget(data);
        const unsubTopic = (0, _tsSdkReactNative.getCommunityStoriesTopic)({
          targetId: param.targetId,
          targetType: param.targetType
        });
        (0, _tsSdkReactNative.subscribeTopic)(unsubTopic);
      }
    });
    return () => unsubscribe();
  }, []);
  const handleReaction = (0, _react.useCallback)(async ({
    targetId,
    reactionName,
    isLiked
  }) => {
    try {
      if (isLiked) {
        await _tsSdkReactNative.ReactionRepository.removeReaction('story', targetId, reactionName);
      } else {
        await _tsSdkReactNative.ReactionRepository.addReaction('story', targetId, reactionName);
      }
    } catch (error) {
      _reactNative.Alert.alert('Error on reaction', error.message);
    }
  }, []);
  return {
    handleReaction,
    loading: fetching,
    getStories,
    stories,
    onNextPage: onNextPageRef.current,
    getStoryTarget,
    storyTarget
  };
};
exports.useStory = useStory;
//# sourceMappingURL=useStory.js.map