import React, { useContext, useEffect, useRef, useState, } from 'react';
/* import NameTag from '../../components/NameTag';
 */ import { useSelector } from 'react-redux';
import { store } from '../../store/store';
import { MediaRoomContext } from '../../services/MediaRoomService';
import { ConfigServiceContext } from '../../utils/ConfigProvider';
/* import VideoStrengthIndicator from '../../components/video/VideoStrengthIndicator';
import PeerAvatar from '../../components/PeerAvatar';
*/
import { MediaStream, RTCView } from 'react-native-webrtc';
import { Flex, Box, Spinner, Button, VStack, Text, Icon } from '../../themes/components';
import { NativeModules, View, Platform } from 'react-native';
import UserAvatar from 'react-native-user-avatar';
import { ThemeContext } from 'styled-components';
import NameTag from '../../components/NameTag';
import VideoTransform from '../../components/video/VideoTransform';
import { useOrientation } from '../../utils/browser-utils';
import borderRadius from '../../themes/foundations/borderRadius';
import VideoStrengthIndicator from "../../components/video/VideoStrengthIndicator";
const { DyteHelper } = NativeModules;
export default function PeerView(props) {
    // const [audioData, setAudioData] = useState(new Uint8Array(0));
    const displayName = useSelector((state) => state.participant.displayName);
    const mediaRoomCtx = useContext(MediaRoomContext);
    const mediaRoom = mediaRoomCtx?.mediaRoom;
    const { sessionConfig } = useContext(ConfigServiceContext);
    const audioTrackRef = useRef();
    const videoTrackRef = useRef();
    const [peerStream, setPeerStream] = useState(new MediaStream(undefined));
    const [videoElem, setVideoElem] = useState(null);
    const { colors } = useContext(ThemeContext);
    const [screenshareHack, setScreenshareHack] = useState(false);
    const { orientation, forced, setForced } = useOrientation();
    const isLandscape = orientation === "LANDSCAPE";
    const { peer, hideBadge, isMobile, totalPeers, size, index, contain, } = props;
    const displayImgSelf = useSelector((state) => state.participant.displayImageURL);
    const activeConsumers = useSelector((state) => state.consumers.activeConsumers);
    const peerId = peer.id;
    const activeConsumer = activeConsumers.find(el => el.peerId === peerId);
    const videoScore = activeConsumer?.score || 10;
    const setAudioTrack = (audioTrack) => {
        if (audioTrackRef.current !== audioTrack) {
            audioTrackRef.current = audioTrack;
            if (audioTrack && false) {
                const stream = new MediaStream(undefined);
                stream.addTrack(audioTrack);
                if (videoTrackRef.current) {
                    stream.addTrack(videoTrackRef.current);
                }
                setPeerStream(stream);
            }
        }
    };
    const setVideoTrack = (videoTrack) => {
        videoTrackRef.current = videoTrack;
        if (videoTrack) {
            const stream = new MediaStream(undefined);
            stream.addTrack(videoTrack);
            if (audioTrackRef.current) {
                stream.addTrack(audioTrackRef.current);
            }
            setPeerStream(stream);
        }
    };
    const shouldMirror = () => {
        try {
            return store.getState().participant.cameraFacing === 'front';
        }
        catch {
            return false;
        }
    };
    useEffect(() => {
        setAudioTrack(peer.audioTrack);
    }, [peer.audioTrack]);
    useEffect(() => {
        if (peer.videoTrack) {
            setVideoTrack(peer.videoTrack);
            setTimeout(() => setScreenshareHack(true), 500);
        }
    }, [peer.videoTrack, peer.videoScore]);
    const onVideoElem = (elem) => {
        setVideoElem(elem);
    };
    // const peerOverlayElement = sessionConfig.peerOverlays[peer.id];
    const { audioMuted, videoVisible } = peer;
    const trimName = (name) => {
        if (!isMobile)
            return name;
        let trimmedName = name;
        if (totalPeers > 2) {
            [trimmedName] = name.split(' ');
            trimmedName = trimmedName.slice(0, 10);
        }
        if (totalPeers > 6) {
            trimmedName = trimmedName.slice(0, 8);
        }
        return trimmedName;
    };
    const toggleOrientation = () => {
        forced ? DyteHelper.resetOrientation() : DyteHelper.forceLandscape();
        setForced((f) => !f);
    };
    const self = trimName(peer.isMe ? displayName : peer.displayName);
    const { height: propsHeight, width, children } = props;
    const height = propsHeight || Math.floor(width * 0.5625);
    const permissions = sessionConfig?.permissions;
    if (videoVisible && (!peerStream || !peer.videoTrack)) {
        return (<Box justify="center" align="center" width={width} height={height} border={`1px solid ${colors.primary[300]}`} borderRadius={borderRadius.medium}>
				<Spinner color="#fff"/>
			</Box>);
    }
    const renderVideo = () => {
        if (peer.screenshare) {
            return (<VideoTransform enabled width={width - 8} height={height - 8} streamId={peer.videoTrack?.id || Math.random().toString()}>
					<RTCView objectFit={contain ? 'contain' : 'cover'} style={{ flex: 1 }} zOrder={0} streamURL={peerStream.toURL()}/>
				</VideoTransform>);
        }
        return (<RTCView objectFit={contain ? 'contain' : 'cover'} style={{ flex: 1 }} mirror={peer.isMe ? shouldMirror() : false} streamURL={peerStream.toURL()} zOrder={1}/>);
    };
    return (<View style={[
        {
            backgroundColor: 'black',
            borderRadius: borderRadius.medium,
            width: width - 8,
            height: height - 8,
            margin: 3,
            overflow: 'hidden',
        }
    ]}>
			<Flex position="absolute" bottom={1}>
				{children}
			</Flex>
			{peer.videoVisible && screenshareHack ? (renderVideo()) : (<Flex bg={colors.videoBackground} width={width - 8} height={height - 8} justify="center" align="center">
					<UserAvatar size={40} src={peer.picture} name={`${peer.displayName}`} bgColor={colors.primary[700]}/>
				</Flex>)}
		<Flex width={width} position="absolute" bottom="10" left={10}>
				{hideBadge || (<Flex justify="flex-start" alignSelf="flex-start" direction="column">
						{!!self
        && (<NameTag audioMuted={audioMuted} audioTrack={peer.audioTrack} name={self} size={isMobile || size === 'sm' ? 'sm' : 'md'} screenshare={peer.screenshare}/>)}
					</Flex>)}
			</Flex>
			<Flex width={width} position="absolute" top="10" right="10"> 
			{videoScore < 10 && (<Box zIndex={5} justify="flex-end" alignSelf="flex-end" direction="column">
						<VideoStrengthIndicator videoScore={videoScore}/>
					</Box>)}
			</Flex>
			{peer.screenshare && (forced || !isLandscape) && Platform.OS === 'android' &&
        <Flex width={width} position="absolute" top="10" right={10}>
				<Flex justify="flex-start" alignSelf={isLandscape ? "flex-start" : "flex-end"} direction="column">
						<Button onClick={toggleOrientation}>
				<VStack width={36} p="2" ml={22} height="36px" bg="secondary.800" borderRadius={borderRadius.medium} align="center" justify="center">
					<Text fontSize="xs">
						<Icon name={forced ? "fullscreen-exit" : "fullscreen"} fill={forced ? colors.danger[500] : colors.textPrimary[100]}/>
					</Text>
				</VStack>
			</Button>
					</Flex>
			</Flex>}
		</View>);
}
PeerView.defaultProps = {
    isMobile: false,
    hideBadge: false,
    height: 0,
    width: 'inherit',
    children: <></>,
    contain: false,
    totalPeers: 0,
    size: 'md',
    isMe: false,
    index: 1,
};
//# sourceMappingURL=PeerView.js.map