import * as React from 'react';
import {VideoItem} from '../../components/video/video';
import {View, Text} from 'react-native';
import {isTwitch} from './twitch';
import {ExternalVideo} from './external';
import {isVimeo} from './vimeo';
import {isYouTube} from './youtube';
import {isMixer} from './mixer';
import {Loading} from '../loading';
import {useFirebase} from '../../hooks/use-firebase/useFirebase';
import VideoPlayerNative from '../video-player-native';

export const VideoPlayer = React.memo(({data}: {data: VideoItem}) => {
  if (!data) return <></>;
  const url = data.data?.metadata?.url || data.renderer?.url;
  const isExternal =
    isTwitch(url) || isVimeo(url) || isYouTube(url) || isMixer(url);

  return (
    <View>
      {isExternal ? (
        <ExternalVideo url={data.data.metadata?.url || data.renderer?.url} />
      ) : !!url ? (
        <VideoPlayerNative
          style={{width: '100%', aspectRatio: 16 / 9}}
          resizeMode="contain"
          source={{uri: url}}
        />
      ) : (
        <Text>Not supported.</Text>
      )}
    </View>
  );
});

export const VideoFetcher = ({id}: {id: string}) => {
  const {loading, data} = useFirebase<VideoItem>(`/objects/${id}`);

  return loading ? <Loading /> : <VideoPlayer data={data as VideoItem} />;
};
