import { useEffect, useState, useRef, useCallback } from 'react';
import { View, TouchableOpacity, TouchableWithoutFeedback, Platform } from 'react-native';
import { useStyles } from './styles';
import LiveStreamEndThumbnail from '../../../components/LivestreamContent/LivestreamEndedThumbnail';
import { SvgXml } from 'react-native-svg';
import { close } from '../../../../core/assets/icons';
import { useNavigation, useRoute } from '@react-navigation/native';
import { RoomStatus } from '../../../enums/roomStatus';
import LiveStreamIdleThumbnail from '../../../components/LivestreamContent/LivestreamIdleThumbnail';
import { Typography } from '../../../../core/components/Typography/Typography';
import { SafeAreaView } from 'react-native-safe-area-context';
import NetInfo from '@react-native-community/netinfo';
import { CircularProgressIndicator } from '../../../components/CircularProgressIndicator';
import Video from 'react-native-video';
import useAuth from '../../../../core/hooks/useAuth';
import { usePostSubscription, useRoomSubscription } from '../../../hooks/index';
import { RoomRepository } from '@amityco/ts-sdk-react-native';
import { useShareableLink } from '../../../../core/hooks/useShareableLink';
import { ShareableLinkModel } from '../../../types';
import { useBottomSheet } from '../../../../core/stores/slices/bottomSheetSlice';
import MenuButton from '../../../elements/MenuButton/MenuButton';
import { CopyLinkAction } from '../../../elements/CopyLinkAction';
import { ShareAction } from '../../../elements/ShareAction';
import { PageID } from '../../../enums';
function AmityLiveStreamPlayerPage() {
  var _post$targetCommunity, _user, _room$recordedPlaybac, _room$recordedPlaybac2, _client$token;
  const {
    styles,
    theme
  } = useStyles();
  const navigation = useNavigation();
  const route = useRoute();
  const [reconnecting, setReconnecting] = useState(false);
  const [room, setRoom] = useState(null);
  const [error, setError] = useState(null);
  const [isVideoLoading, setIsVideoLoading] = useState(true);
  const [videoKey, setVideoKey] = useState(0);
  const [isPaused, setIsPaused] = useState(false);
  const [wasLive, setWasLive] = useState(false);
  const [showControls, setShowControls] = useState(true);
  const controlsTimerRef = useRef(null);
  const {
    roomId,
    post
  } = route.params;
  const {
    subscribedPost
  } = usePostSubscription(post === null || post === void 0 ? void 0 : post.postId);
  const {
    getShareLink
  } = useShareableLink();
  const {
    openBottomSheet,
    bottomSheetHeight
  } = 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(ShareableLinkModel.livestreams, roomId) : null;
  const handleSharePress = () => {
    if (!shareLink) return;
    openBottomSheet({
      dark: true,
      height: bottomSheetHeight[2],
      content: /*#__PURE__*/React.createElement(View, null, /*#__PURE__*/React.createElement(CopyLinkAction, {
        dark: true,
        link: shareLink,
        pageId: PageID.livestream_player_page
      }), /*#__PURE__*/React.createElement(ShareAction, {
        dark: true,
        link: shareLink,
        pageId: PageID.livestream_player_page
      }))
    });
  };
  useRoomSubscription({
    room
  });
  const {
    client
  } = useAuth();
  const videoRef = useRef(null);
  const isStreamEnding = useRef(false);
  useEffect(() => {
    const unsubscribe = RoomRepository.getRoom(roomId, ({
      data,
      loading,
      error: streamError
    }) => {
      if (streamError) setError(streamError);
      if (!loading && data) setRoom({
        ...data
      });
    });
    return () => unsubscribe();
  }, [roomId]);
  useEffect(() => {
    if ((room === null || room === void 0 ? void 0 : room.status) === RoomStatus.live) {
      setWasLive(true);
    }
  }, [room === null || room === void 0 ? void 0 : room.status]);
  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]);
  useEffect(() => {
    const unsubscribe = NetInfo.addEventListener(state => {
      setReconnecting(!state.isConnected);
    });
    return () => unsubscribe();
  }, []);
  useEffect(() => {
    if (!(room !== null && room !== void 0 && room.status)) return;
    const shouldEnd = room.status === RoomStatus.ended || room.status === RoomStatus.recorded && wasLive;
    if (!shouldEnd || isStreamEnding.current) return;
    isStreamEnding.current = true;
    setIsPaused(true);
    if (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]);
  useEffect(() => {
    if ((room === null || room === void 0 ? void 0 : room.status) === RoomStatus.terminated) {
      navigation.replace('LivestreamTerminated', {
        type: 'viewer'
      });
    }
  }, [room === null || room === void 0 ? void 0 : room.status, navigation]);
  const showControlsTemporarily = useCallback(() => {
    setShowControls(true);
    if (controlsTimerRef.current) clearTimeout(controlsTimerRef.current);
    controlsTimerRef.current = setTimeout(() => setShowControls(false), 4000);
  }, []);
  useEffect(() => {
    showControlsTemporarily();
    return () => {
      if (controlsTimerRef.current) clearTimeout(controlsTimerRef.current);
    };
  }, [showControlsTemporarily]);
  const shouldShowEndThumbnail = (room === null || room === void 0 ? void 0 : room.status) === RoomStatus.ended || (room === null || room === void 0 ? void 0 : room.status) === 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(SafeAreaView, {
      style: styles.container
    }, /*#__PURE__*/React.createElement(LiveStreamIdleThumbnail, null));
  }
  const closePlayer = () => {
    navigation.goBack();
  };
  const videoUrl = room.status === RoomStatus.recorded ? (_room$recordedPlaybac = room.recordedPlaybackInfos[0]) === null || _room$recordedPlaybac === void 0 ? void 0 : _room$recordedPlaybac.url : room.livePlaybackUrl;
  return /*#__PURE__*/React.createElement(SafeAreaView, {
    style: styles.container
  }, shouldShowEndThumbnail ? /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(View, {
    style: styles.steamEndContainer
  }, /*#__PURE__*/React.createElement(LiveStreamEndThumbnail, null)), /*#__PURE__*/React.createElement(TouchableOpacity, {
    style: styles.closeButton,
    onPress: closePlayer
  }, /*#__PURE__*/React.createElement(SvgXml, {
    xml: close(),
    width: "24",
    height: "24",
    color: theme.colors.background
  }))) : /*#__PURE__*/React.createElement(TouchableWithoutFeedback, {
    onPress: showControlsTemporarily
  }, /*#__PURE__*/React.createElement(View, {
    style: styles.container
  }, !shouldShowEndThumbnail && /*#__PURE__*/React.createElement(Video, {
    key: Platform.OS === 'android' ? `${videoUrl}-${videoKey}` : videoUrl,
    ref: videoRef,
    source: {
      uri: room.status === 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.recorded) {
        setIsPaused(false);
      }
    }
  }), (room.status === RoomStatus.live || room.status === RoomStatus.waitingReconnect) && /*#__PURE__*/React.createElement(View, {
    style: styles.liveRow
  }, /*#__PURE__*/React.createElement(View, {
    style: styles.status
  }, /*#__PURE__*/React.createElement(Typography.CaptionBold, {
    style: styles.live
  }, "LIVE")), shareLink && /*#__PURE__*/React.createElement(MenuButton, {
    pageId: PageID.livestream_player_page,
    variant: "vertical",
    onPress: handleSharePress
  })), showControls && /*#__PURE__*/React.createElement(TouchableOpacity, {
    style: styles.liveCloseButton,
    onPress: closePlayer
  }, /*#__PURE__*/React.createElement(SvgXml, {
    xml: close(),
    width: "24",
    height: "24",
    color: theme.colors.background
  })), isVideoLoading && /*#__PURE__*/React.createElement(View, {
    style: styles.connecting
  }, /*#__PURE__*/React.createElement(CircularProgressIndicator, {
    size: 40,
    strokeWidth: 2
  })))), (room.status === RoomStatus.live && reconnecting || room.status === RoomStatus.waitingReconnect) && /*#__PURE__*/React.createElement(View, {
    style: styles.connecting
  }, /*#__PURE__*/React.createElement(CircularProgressIndicator, {
    size: 40,
    strokeWidth: 2
  }), /*#__PURE__*/React.createElement(Typography.TitleBold, {
    style: styles.text
  }, "Reconnecting"), /*#__PURE__*/React.createElement(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.")));
}
export default AmityLiveStreamPlayerPage;
//# sourceMappingURL=Player.js.map