"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _react = require("react");
var _reactNative = require("react-native");
var _styles = require("./styles");
var _LivestreamEndedThumbnail = _interopRequireDefault(require("../../../components/LivestreamContent/LivestreamEndedThumbnail"));
var _reactNativeSvg = require("react-native-svg");
var _icons = require("../../../../core/assets/icons");
var _native = require("@react-navigation/native");
var _roomStatus = require("../../../enums/roomStatus");
var _LivestreamIdleThumbnail = _interopRequireDefault(require("../../../components/LivestreamContent/LivestreamIdleThumbnail"));
var _Typography = require("../../../../core/components/Typography/Typography");
var _reactNativeSafeAreaContext = require("react-native-safe-area-context");
var _netinfo = _interopRequireDefault(require("@react-native-community/netinfo"));
var _CircularProgressIndicator = require("../../../components/CircularProgressIndicator");
var _reactNativeVideo = _interopRequireDefault(require("react-native-video"));
var _useAuth = _interopRequireDefault(require("../../../../core/hooks/useAuth"));
var _index = require("../../../hooks/index");
var _tsSdkReactNative = require("@amityco/ts-sdk-react-native");
var _useShareableLink = require("../../../../core/hooks/useShareableLink");
var _types = require("../../../types");
var _bottomSheetSlice = require("../../../../core/stores/slices/bottomSheetSlice");
var _MenuButton = _interopRequireDefault(require("../../../elements/MenuButton/MenuButton"));
var _CopyLinkAction = require("../../../elements/CopyLinkAction");
var _ShareAction = require("../../../elements/ShareAction");
var _enums = require("../../../enums");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
function AmityLiveStreamPlayerPage() {
  var _post$targetCommunity, _user, _room$recordedPlaybac, _room$recordedPlaybac2, _client$token;
  const {
    styles,
    theme
  } = (0, _styles.useStyles)();
  const navigation = (0, _native.useNavigation)();
  const route = (0, _native.useRoute)();
  const [reconnecting, setReconnecting] = (0, _react.useState)(false);
  const [room, setRoom] = (0, _react.useState)(null);
  const [error, setError] = (0, _react.useState)(null);
  const [isVideoLoading, setIsVideoLoading] = (0, _react.useState)(true);
  const [videoKey, setVideoKey] = (0, _react.useState)(0);
  const [isPaused, setIsPaused] = (0, _react.useState)(false);
  const [wasLive, setWasLive] = (0, _react.useState)(false);
  const [showControls, setShowControls] = (0, _react.useState)(true);
  const controlsTimerRef = (0, _react.useRef)(null);
  const {
    roomId,
    post
  } = route.params;
  const {
    subscribedPost
  } = (0, _index.usePostSubscription)(post === null || post === void 0 ? void 0 : post.postId);
  const {
    getShareLink
  } = (0, _useShareableLink.useShareableLink)();
  const {
    openBottomSheet,
    bottomSheetHeight
  } = (0, _bottomSheetSlice.useBottomSheet)();
  const canShare = (post === null || post === void 0 ? void 0 : post.targetType) === 'user' || (post === null || post === void 0 ? void 0 : post.targetType) === 'community' && !!(post !== null && post !== void 0 && (_post$targetCommunity = post.targetCommunity) !== null && _post$targetCommunity !== void 0 && _post$targetCommunity.isPublic);
  const shareLink = canShare ? getShareLink(_types.ShareableLinkModel.livestreams, roomId) : null;
  const handleSharePress = () => {
    if (!shareLink) return;
    openBottomSheet({
      dark: true,
      height: bottomSheetHeight[2],
      content: /*#__PURE__*/React.createElement(_reactNative.View, null, /*#__PURE__*/React.createElement(_CopyLinkAction.CopyLinkAction, {
        dark: true,
        link: shareLink,
        pageId: _enums.PageID.livestream_player_page
      }), /*#__PURE__*/React.createElement(_ShareAction.ShareAction, {
        dark: true,
        link: shareLink,
        pageId: _enums.PageID.livestream_player_page
      }))
    });
  };
  (0, _index.useRoomSubscription)({
    room
  });
  const {
    client
  } = (0, _useAuth.default)();
  const videoRef = (0, _react.useRef)(null);
  const isStreamEnding = (0, _react.useRef)(false);
  (0, _react.useEffect)(() => {
    const unsubscribe = _tsSdkReactNative.RoomRepository.getRoom(roomId, ({
      data,
      loading,
      error: streamError
    }) => {
      if (streamError) setError(streamError);
      if (!loading && data) setRoom({
        ...data
      });
    });
    return () => unsubscribe();
  }, [roomId]);
  (0, _react.useEffect)(() => {
    if ((room === null || room === void 0 ? void 0 : room.status) === _roomStatus.RoomStatus.live) {
      setWasLive(true);
    }
  }, [room === null || room === void 0 ? void 0 : room.status]);
  (0, _react.useEffect)(() => {
    if (room !== null && room !== void 0 && room.isDeleted || subscribedPost !== null && subscribedPost !== void 0 && subscribedPost.isDeleted) {
      navigation.replace('PostDetail', {
        postId: subscribedPost === null || subscribedPost === void 0 ? void 0 : subscribedPost.postId,
        isDeleted: subscribedPost === null || subscribedPost === void 0 ? void 0 : subscribedPost.isDeleted
      });
    }
  }, [navigation, room === null || room === void 0 ? void 0 : room.isDeleted, subscribedPost === null || subscribedPost === void 0 ? void 0 : subscribedPost.postId, subscribedPost === null || subscribedPost === void 0 ? void 0 : subscribedPost.isDeleted]);
  (0, _react.useEffect)(() => {
    const unsubscribe = _netinfo.default.addEventListener(state => {
      setReconnecting(!state.isConnected);
    });
    return () => unsubscribe();
  }, []);
  (0, _react.useEffect)(() => {
    if (!(room !== null && room !== void 0 && room.status)) return;
    const shouldEnd = room.status === _roomStatus.RoomStatus.ended || room.status === _roomStatus.RoomStatus.recorded && wasLive;
    if (!shouldEnd || isStreamEnding.current) return;
    isStreamEnding.current = true;
    setIsPaused(true);
    if (_reactNative.Platform.OS === 'ios') {
      // iOS: ONLY dismiss fullscreen. DO NOT touch key. DO NOT unmount.
      requestAnimationFrame(() => {
        var _videoRef$current, _videoRef$current$dis;
        (_videoRef$current = videoRef.current) === null || _videoRef$current === void 0 || (_videoRef$current$dis = _videoRef$current.dismissFullscreenPlayer) === null || _videoRef$current$dis === void 0 || _videoRef$current$dis.call(_videoRef$current);
      });
    } else {
      // Android: HARD destroy
      setTimeout(() => {
        setVideoKey(prev => prev + 1);
      }, 50);
    }
  }, [room === null || room === void 0 ? void 0 : room.status, wasLive]);
  (0, _react.useEffect)(() => {
    if ((room === null || room === void 0 ? void 0 : room.status) === _roomStatus.RoomStatus.terminated) {
      navigation.replace('LivestreamTerminated', {
        type: 'viewer'
      });
    }
  }, [room === null || room === void 0 ? void 0 : room.status, navigation]);
  const showControlsTemporarily = (0, _react.useCallback)(() => {
    setShowControls(true);
    if (controlsTimerRef.current) clearTimeout(controlsTimerRef.current);
    controlsTimerRef.current = setTimeout(() => setShowControls(false), 4000);
  }, []);
  (0, _react.useEffect)(() => {
    showControlsTemporarily();
    return () => {
      if (controlsTimerRef.current) clearTimeout(controlsTimerRef.current);
    };
  }, [showControlsTemporarily]);
  const shouldShowEndThumbnail = (room === null || room === void 0 ? void 0 : room.status) === _roomStatus.RoomStatus.ended || (room === null || room === void 0 ? void 0 : room.status) === _roomStatus.RoomStatus.recorded && wasLive || (room === null || room === void 0 || (_user = room.user) === null || _user === void 0 ? void 0 : _user.isGlobalBan);
  if (!room || error) {
    return /*#__PURE__*/React.createElement(_reactNativeSafeAreaContext.SafeAreaView, {
      style: styles.container
    }, /*#__PURE__*/React.createElement(_LivestreamIdleThumbnail.default, null));
  }
  const closePlayer = () => {
    navigation.goBack();
  };
  const videoUrl = room.status === _roomStatus.RoomStatus.recorded ? (_room$recordedPlaybac = room.recordedPlaybackInfos[0]) === null || _room$recordedPlaybac === void 0 ? void 0 : _room$recordedPlaybac.url : room.livePlaybackUrl;
  return /*#__PURE__*/React.createElement(_reactNativeSafeAreaContext.SafeAreaView, {
    style: styles.container
  }, shouldShowEndThumbnail ? /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(_reactNative.View, {
    style: styles.steamEndContainer
  }, /*#__PURE__*/React.createElement(_LivestreamEndedThumbnail.default, null)), /*#__PURE__*/React.createElement(_reactNative.TouchableOpacity, {
    style: styles.closeButton,
    onPress: closePlayer
  }, /*#__PURE__*/React.createElement(_reactNativeSvg.SvgXml, {
    xml: (0, _icons.close)(),
    width: "24",
    height: "24",
    color: theme.colors.background
  }))) : /*#__PURE__*/React.createElement(_reactNative.TouchableWithoutFeedback, {
    onPress: showControlsTemporarily
  }, /*#__PURE__*/React.createElement(_reactNative.View, {
    style: styles.container
  }, !shouldShowEndThumbnail && /*#__PURE__*/React.createElement(_reactNativeVideo.default, {
    key: _reactNative.Platform.OS === 'android' ? `${videoUrl}-${videoKey}` : videoUrl,
    ref: videoRef,
    source: {
      uri: room.status === _roomStatus.RoomStatus.recorded ? (_room$recordedPlaybac2 = room.recordedPlaybackInfos[0]) === null || _room$recordedPlaybac2 === void 0 ? void 0 : _room$recordedPlaybac2.url : room.livePlaybackUrl,
      headers: {
        Authorization: `Bearer ${client === null || client === void 0 || (_client$token = client.token) === null || _client$token === void 0 ? void 0 : _client$token.accessToken}`
      },
      type: 'm3u8'
    },
    style: styles.container,
    resizeMode: "contain",
    controls: false,
    paused: isPaused,
    muted: false,
    volume: 1.0,
    audioOutput: "speaker",
    playInBackground: false,
    playWhenInactive: false,
    repeat: false,
    onLoad: () => {
      setIsVideoLoading(false);
      if (room.status === _roomStatus.RoomStatus.recorded) {
        setIsPaused(false);
      }
    }
  }), (room.status === _roomStatus.RoomStatus.live || room.status === _roomStatus.RoomStatus.waitingReconnect) && /*#__PURE__*/React.createElement(_reactNative.View, {
    style: styles.liveRow
  }, _reactNative.Platform.OS !== 'android' && /*#__PURE__*/React.createElement(_reactNative.View, {
    style: styles.status
  }, /*#__PURE__*/React.createElement(_Typography.Typography.CaptionBold, {
    style: styles.live
  }, "LIVE")), shareLink && /*#__PURE__*/React.createElement(_MenuButton.default, {
    pageId: _enums.PageID.livestream_player_page,
    variant: "vertical",
    onPress: handleSharePress
  })), showControls && /*#__PURE__*/React.createElement(_reactNative.TouchableOpacity, {
    style: styles.liveCloseButton,
    onPress: closePlayer
  }, /*#__PURE__*/React.createElement(_reactNativeSvg.SvgXml, {
    xml: (0, _icons.close)(),
    width: "24",
    height: "24",
    color: theme.colors.background
  })), isVideoLoading && /*#__PURE__*/React.createElement(_reactNative.View, {
    style: styles.connecting
  }, /*#__PURE__*/React.createElement(_CircularProgressIndicator.CircularProgressIndicator, {
    size: 40,
    strokeWidth: 2
  })))), (room.status === _roomStatus.RoomStatus.live && reconnecting || room.status === _roomStatus.RoomStatus.waitingReconnect) && /*#__PURE__*/React.createElement(_reactNative.View, {
    style: styles.connecting
  }, /*#__PURE__*/React.createElement(_CircularProgressIndicator.CircularProgressIndicator, {
    size: 40,
    strokeWidth: 2
  }), /*#__PURE__*/React.createElement(_Typography.Typography.TitleBold, {
    style: styles.text
  }, "Reconnecting"), /*#__PURE__*/React.createElement(_Typography.Typography.Caption, {
    style: styles.reconnectingText
  }, "Due to poor connection, this live stream has been ", '\n', " paused. It will resume automatically ", '\n', " once the connection is stable.")));
}
var _default = exports.default = AmityLiveStreamPlayerPage;
//# sourceMappingURL=Player.js.map