"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = exports.StoryListItem = void 0;
var _react = require("react");
var _reactNative = require("react-native");
var _reactNativeSwipeGestures = _interopRequireDefault(require("react-native-swipe-gestures"));
var _helpers = require("./helpers");
var _reactNativeVideo = _interopRequireDefault(require("react-native-video"));
var _native = require("@react-navigation/native");
var _reactNativeSvg = require("react-native-svg");
var _xml = require("../../../../../core/assets/icons/xml");
var _styles = require("./styles");
var _useTimeDifference = require("../../../../../core/hooks/useTimeDifference");
var _useStory = require("../../../../../core/hooks/useStory");
var _tsSdkReactNative = require("@amityco/ts-sdk-react-native");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
const StoryListItem = ({
  index,
  key,
  userId,
  profileImage,
  profileName,
  duration,
  onFinish,
  onClosePress,
  stories,
  currentPage,
  onStorySeen,
  renderCloseComponent,
  renderSwipeUpComponent,
  renderTextComponent,
  loadedAnimationBarStyle,
  unloadedAnimationBarStyle,
  animationBarContainerStyle,
  storyUserContainerStyle,
  storyImageStyle,
  storyAvatarImageStyle,
  storyContainerStyle
}) => {
  var _content$current;
  const styles = (0, _styles.useStyles)();
  const [load, setLoad] = (0, _react.useState)(true);
  const [pressed, setPressed] = (0, _react.useState)(false);
  const [content, setContent] = (0, _react.useState)(stories.map(x => ({
    ...x,
    finish: 0
  })));
  const [current, setCurrent] = (0, _react.useState)(0);
  const [storyDuration, setStoryDuration] = (0, _react.useState)(duration);
  const [currentSeek, setCurrentSeek] = (0, _react.useState)(0);
  const progress = (0, _react.useRef)(new _reactNative.Animated.Value(0)).current;
  const timeDifference = (0, _useTimeDifference.useTimeDifference)(content[current].createdAt, true);
  const storyHyperLink = ((_content$current = content[current]) === null || _content$current === void 0 || (_content$current = _content$current.items[0]) === null || _content$current === void 0 ? void 0 : _content$current.data) || undefined;
  const creatorName = content[current].creatorName ?? '';
  const viewer = content[current].viewer ?? 0;
  const comments = content[current].comments ?? [];
  const storyId = content[current].story_id;
  const [totalReaction, setTotalReaction] = (0, _react.useState)(0);
  const [isLiked, setIsLiked] = (0, _react.useState)(false);
  const {
    handleReaction
  } = (0, _useStory.useStory)();
  const prevCurrentPage = (0, _helpers.usePrevious)(currentPage);
  (0, _native.useFocusEffect)((0, _react.useCallback)(() => {
    const unsubscribe = _tsSdkReactNative.StoryRepository.getStoryByStoryId(storyId, ({
      error,
      loading,
      data
    }) => {
      if (error) return;
      if (!loading) {
        const myReaction = data.myReactions ?? [];
        setIsLiked(myReaction.length > 0);
        setTotalReaction(data.reactionsCount);
      }
    });
    return () => {
      setPressed(true);
      unsubscribe();
    };
  }, [storyId]));
  (0, _react.useEffect)(() => {
    let isPrevious = !!prevCurrentPage && +prevCurrentPage > +currentPage;
    if (isPrevious) {
      setCurrent(content.length - 1);
    } else {
      setCurrent(0);
    }
    let data = [...content];
    data.map((x, i) => {
      if (isPrevious) {
        x.finish = 1;
        if (i === content.length - 1) {
          x.finish = 0;
        }
      } else {
        x.finish = 0;
      }
    });
    setContent(data);
    start();
  }, [currentPage]);
  const prevCurrent = (0, _helpers.usePrevious)(current);
  (0, _react.useEffect)(() => {
    if (!(0, _helpers.isNullOrWhitespace)(prevCurrent)) {
      if (prevCurrent) {
        if (+current > +prevCurrent && content[current - 1].story_image === content[current].story_image) {
          start();
        } else if (+current < +prevCurrent && content[current + 1].story_image === content[current].story_image) {
          start();
        }
      }
    }
  }, [current]);
  function start() {
    setLoad(false);
    progress.setValue(0);
    startAnimation();
  }
  function startAnimation() {
    _reactNative.Animated.timing(progress, {
      toValue: 1,
      duration: storyDuration - currentSeek * 1000,
      useNativeDriver: false
    }).start(({
      finished
    }) => {
      if (finished) {
        next();
      }
    });
  }
  function onSwipeUp(_props) {
    if (onClosePress) {
      onClosePress();
    }
    if (content[current].onPress) {
      var _content$current$onPr, _content$current2;
      (_content$current$onPr = (_content$current2 = content[current]).onPress) === null || _content$current$onPr === void 0 || _content$current$onPr.call(_content$current2);
    }
  }
  function onSwipeDown(_props) {
    onClosePress();
  }
  const config = {
    velocityThreshold: 0.3,
    directionalOffsetThreshold: 80
  };
  function next() {
    setCurrentSeek(0);
    // check if the next content is not empty
    setLoad(true);
    if (current !== content.length - 1) {
      let data = [...content];
      data[current].finish = 1;
      setContent(data);
      setCurrent(current + 1);
      progress.setValue(0);
    } else {
      // the next content is empty
      close('next');
    }
  }
  function previous() {
    setCurrentSeek(0);
    // checking if the previous content is not empty
    setLoad(true);
    if (current - 1 >= 0) {
      let data = [...content];
      data[current].finish = 0;
      setContent(data);
      setCurrent(current - 1);
      progress.setValue(0);
    } else {
      // the previous content is empty
      close('previous');
    }
  }
  function close(state) {
    let data = [...content];
    data.map(x => x.finish = 0);
    setContent(data);
    progress.setValue(0);
    if (currentPage === index) {
      if (onFinish) {
        onFinish(state);
      }
    }
  }
  const onPressHyperLink = (0, _react.useCallback)(async () => {
    const supported = await _reactNative.Linking.canOpenURL(storyHyperLink === null || storyHyperLink === void 0 ? void 0 : storyHyperLink.url);
    if (supported) {
      await _reactNative.Linking.openURL(storyHyperLink === null || storyHyperLink === void 0 ? void 0 : storyHyperLink.url);
    } else {
      _reactNative.Alert.alert(`Don't know how to open this URL: ${storyHyperLink === null || storyHyperLink === void 0 ? void 0 : storyHyperLink.url}`);
    }
  }, [storyHyperLink === null || storyHyperLink === void 0 ? void 0 : storyHyperLink.url]);
  (0, _react.useEffect)(() => {
    if (onStorySeen && currentPage === index) {
      onStorySeen({
        user_id: userId,
        user_image: profileImage,
        user_name: profileName,
        story: content[current]
      });
    }
  }, [currentPage, index, onStorySeen, current]);
  const handleLoadVideo = data => {
    setStoryDuration(data.duration * 1000);
  };
  const onPressReaction = (0, _react.useCallback)(() => {
    handleReaction({
      targetId: storyId,
      reactionName: 'like',
      isLiked
    });
    setTotalReaction(prev => isLiked ? prev - 1 : prev + 1);
    setIsLiked(prev => !prev);
  }, [storyId, isLiked]);
  return /*#__PURE__*/React.createElement(_reactNativeSwipeGestures.default, {
    key: key,
    onSwipeUp: onSwipeUp,
    onSwipeDown: onSwipeDown,
    config: config,
    style: [styles.container, storyContainerStyle]
  }, /*#__PURE__*/React.createElement(_reactNative.SafeAreaView, null, /*#__PURE__*/React.createElement(_reactNative.View, {
    style: styles.backgroundContainer
  }, content[current].story_type === 'video' ? /*#__PURE__*/React.createElement(_reactNativeVideo.default, {
    onProgress: ({
      currentTime
    }) => setCurrentSeek(currentTime),
    source: {
      uri: content[current].story_video
    },
    style: styles.video,
    resizeMode: "contain",
    controls: false,
    onReadyForDisplay: () => start(),
    paused: content[current].story_page !== currentPage ? true : pressed,
    onLoad: handleLoadVideo
  }) : /*#__PURE__*/React.createElement(_reactNative.Image, {
    onLoadEnd: () => start(),
    source: {
      uri: content[current].story_image
    },
    style: [styles.image, storyImageStyle],
    resizeMode: "contain"
  }), load && /*#__PURE__*/React.createElement(_reactNative.View, {
    style: styles.spinnerContainer
  }, /*#__PURE__*/React.createElement(_reactNative.ActivityIndicator, {
    size: "large",
    color: 'white'
  })))), /*#__PURE__*/React.createElement(_reactNative.View, {
    style: styles.flexCol
  }, /*#__PURE__*/React.createElement(_reactNative.View, {
    style: [styles.animationBarContainer, animationBarContainerStyle]
  }, content.map((_index, animKey) => {
    return /*#__PURE__*/React.createElement(_reactNative.View, {
      key: animKey,
      style: [styles.animationBackground, unloadedAnimationBarStyle]
    }, /*#__PURE__*/React.createElement(_reactNative.Animated.View, {
      style: [{
        flex: current === animKey ? progress : content[animKey].finish
      }, styles.animationBar, loadedAnimationBarStyle]
    }));
  })), /*#__PURE__*/React.createElement(_reactNative.View, {
    style: [styles.userContainer, storyUserContainerStyle]
  }, /*#__PURE__*/React.createElement(_reactNative.View, {
    style: styles.flexRowCenter
  }, /*#__PURE__*/React.createElement(_reactNative.Image, {
    style: [styles.avatarImage, storyAvatarImageStyle],
    source: {
      uri: profileImage
    }
  }), typeof renderTextComponent === 'function' ? renderTextComponent({
    item: content[current],
    profileName
  }) : /*#__PURE__*/React.createElement(_reactNative.View, null, /*#__PURE__*/React.createElement(_reactNative.Text, {
    style: styles.avatarText
  }, profileName), /*#__PURE__*/React.createElement(_reactNative.View, {
    style: styles.flexRowCenter
  }, /*#__PURE__*/React.createElement(_reactNative.Text, {
    style: styles.avatarText
  }, timeDifference), /*#__PURE__*/React.createElement(_reactNative.Text, {
    style: styles.avatarText
  }, "."), /*#__PURE__*/React.createElement(_reactNative.Text, {
    style: styles.avatarText
  }, creatorName)))), /*#__PURE__*/React.createElement(_reactNative.View, {
    style: styles.closeIconContainer
  }, typeof renderCloseComponent === 'function' ? renderCloseComponent({
    onPress: onClosePress,
    item: content[current]
  }) : /*#__PURE__*/React.createElement(_reactNative.TouchableOpacity, {
    onPress: () => {
      if (onClosePress) {
        onClosePress();
      }
    }
  }, /*#__PURE__*/React.createElement(_reactNative.Text, {
    style: styles.whiteText
  }, "X")))), /*#__PURE__*/React.createElement(_reactNative.View, {
    style: styles.pressContainer
  }, /*#__PURE__*/React.createElement(_reactNative.TouchableWithoutFeedback, {
    onPressIn: () => progress.stopAnimation(),
    onLongPress: () => setPressed(true),
    delayLongPress: 300,
    onPressOut: () => {
      setPressed(false);
      startAnimation();
    },
    onPress: () => {
      if (!pressed && !load) {
        previous();
      }
    }
  }, /*#__PURE__*/React.createElement(_reactNative.View, {
    style: styles.flex
  })), /*#__PURE__*/React.createElement(_reactNative.TouchableWithoutFeedback, {
    onPressIn: () => progress.stopAnimation(),
    onLongPress: () => setPressed(true),
    delayLongPress: 300,
    onPressOut: () => {
      setPressed(false);
      startAnimation();
    },
    onPress: () => {
      if (!pressed && !load) {
        next();
      }
    }
  }, /*#__PURE__*/React.createElement(_reactNative.View, {
    style: styles.flex
  })), storyHyperLink && /*#__PURE__*/React.createElement(_reactNative.TouchableOpacity, {
    style: styles.hyperlinkContainer,
    onPress: onPressHyperLink
  }, /*#__PURE__*/React.createElement(_reactNativeSvg.SvgXml, {
    xml: (0, _xml.storyHyperLinkIcon)('blue'),
    width: "25",
    height: "25"
  }), /*#__PURE__*/React.createElement(_reactNative.Text, null, storyHyperLink.customText)))), typeof renderSwipeUpComponent === 'function' ? renderSwipeUpComponent({
    onPress: onSwipeUp,
    item: content[current]
  }) : /*#__PURE__*/React.createElement(_reactNative.View, {
    style: styles.footer
  }, /*#__PURE__*/React.createElement(_reactNative.TouchableOpacity, {
    style: styles.seenContainer
  }, /*#__PURE__*/React.createElement(_reactNativeSvg.SvgXml, {
    xml: (0, _xml.seenIcon)(),
    width: "25",
    height: "25"
  }), /*#__PURE__*/React.createElement(_reactNative.Text, {
    style: styles.seen
  }, viewer)), /*#__PURE__*/React.createElement(_reactNative.View, {
    style: styles.seenContainer
  }, /*#__PURE__*/React.createElement(_reactNative.TouchableOpacity, {
    style: styles.iconContainer
  }, /*#__PURE__*/React.createElement(_reactNativeSvg.SvgXml, {
    xml: (0, _xml.storyCommentIcon)(),
    width: "25",
    height: "25"
  }), /*#__PURE__*/React.createElement(_reactNative.Text, {
    style: styles.seen
  }, comments.length)), /*#__PURE__*/React.createElement(_reactNative.TouchableOpacity, {
    style: styles.iconContainer,
    onPress: onPressReaction
  }, /*#__PURE__*/React.createElement(_reactNativeSvg.SvgXml, {
    xml: isLiked ? _xml.storyLikedIcon : _xml.storyLikeIcon,
    width: "25",
    height: "25"
  }), /*#__PURE__*/React.createElement(_reactNative.Text, {
    style: styles.seen
  }, totalReaction)))));
};
exports.StoryListItem = StoryListItem;
var _default = exports.default = StoryListItem;
StoryListItem.defaultProps = {
  duration: 10000
};
//# sourceMappingURL=StoryListItem.js.map