"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const react_1 = __importStar(require("react"));
/* import NameTag from '@src/components/NameTag';
 */ const react_redux_1 = require("react-redux");
const store_1 = require("../../store/store");
const MediaRoomService_1 = require("../../services/MediaRoomService");
const ConfigProvider_1 = require("../../utils/ConfigProvider");
/* import VideoStrengthIndicator from '@src/components/video/VideoStrengthIndicator';
import PeerAvatar from '@src/components/PeerAvatar';
*/
const react_native_webrtc_1 = require("react-native-webrtc");
const components_1 = require("../../themes/components");
const react_native_1 = require("react-native");
const react_native_user_avatar_1 = __importDefault(require("react-native-user-avatar"));
const styled_components_1 = require("styled-components");
const NameTag_1 = __importDefault(require("../NameTag"));
const VideoTransform_1 = __importDefault(require("./VideoTransform"));
const OrientationContext_1 = require("../../services/OrientationContext");
const borderRadius_1 = __importDefault(require("../../themes/foundations/borderRadius"));
const VideoStrengthIndicator_1 = __importDefault(require("./VideoStrengthIndicator"));
const { DyteHelper } = react_native_1.NativeModules;
function PeerView(props) {
    // const [audioData, setAudioData] = useState(new Uint8Array(0));
    const displayName = react_redux_1.useSelector((state) => state.participant.displayName);
    const mediaRoomCtx = react_1.useContext(MediaRoomService_1.MediaRoomContext);
    const mediaRoom = mediaRoomCtx === null || mediaRoomCtx === void 0 ? void 0 : mediaRoomCtx.mediaRoom;
    const { meeting, sessionConfig } = react_1.useContext(ConfigProvider_1.ConfigServiceContext);
    const activeSpeakerPeerId = react_redux_1.useSelector((state) => state.room.activeSpeakerPeerId);
    const audioTrackRef = react_1.useRef();
    const videoTrackRef = react_1.useRef();
    const [peerStream, setPeerStream] = react_1.useState(new react_native_webrtc_1.MediaStream(undefined));
    const [videoElem, setVideoElem] = react_1.useState(null);
    const { colors } = react_1.useContext(styled_components_1.ThemeContext);
    const [screenshareHack, setScreenshareHack] = react_1.useState(false);
    const { orientation, forced, setForced } = react_1.default.useContext(OrientationContext_1.OrientationContext);
    const isLandscape = orientation === 'LANDSCAPE';
    const { peer, hideBadge, isMobile, totalPeers, size, index, contain, zIndex, } = props;
    const displayImgSelf = react_redux_1.useSelector((state) => state.participant.displayImageURL);
    const activeConsumers = react_redux_1.useSelector((state) => state.consumers.activeConsumers);
    const peerId = peer.id;
    const activeConsumer = activeConsumers.find((el) => el.peerId === peerId);
    const videoScore = (activeConsumer === null || activeConsumer === void 0 ? void 0 : activeConsumer.score) || 10;
    const setAudioTrack = (audioTrack) => {
        if (audioTrackRef.current !== audioTrack) {
            audioTrackRef.current = audioTrack;
            if (audioTrack && false) {
                const stream = new react_native_webrtc_1.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 react_native_webrtc_1.MediaStream(undefined);
            stream.addTrack(videoTrack);
            if (audioTrackRef.current) {
                stream.addTrack(audioTrackRef.current);
            }
            setPeerStream(stream);
        }
    };
    const shouldMirror = () => {
        try {
            return store_1.store.getState().participant.cameraFacing === 'front';
        }
        catch (_a) {
            return false;
        }
    };
    react_1.useEffect(() => {
        setAudioTrack(peer.audioTrack);
    }, [peer.audioTrack]);
    react_1.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 = () => {
        const to = forced
            ? DyteHelper.resetOrientation
            : DyteHelper.forceLandscape;
        to();
        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 === null || sessionConfig === void 0 ? void 0 : sessionConfig.permissions;
    if (videoVisible && (!peerStream || !peer.videoTrack)) {
        return (react_1.default.createElement(components_1.Box, { justify: "center", align: "center", width: width, height: height, border: `1px solid ${colors.primary[300]}`, borderRadius: borderRadius_1.default.medium },
            react_1.default.createElement(components_1.Spinner, { color: "#fff" })));
    }
    const renderVideo = () => {
        var _a;
        if (peer.screenshare) {
            return (react_1.default.createElement(VideoTransform_1.default, { noMovementWithoutScale: true, width: width - 8, height: height - 8, streamId: ((_a = peer.videoTrack) === null || _a === void 0 ? void 0 : _a.id) || Math.random().toString() },
                react_1.default.createElement(react_native_webrtc_1.RTCView
                // @ts-ignore
                , { 
                    // @ts-ignore
                    objectFit: contain ? 'contain' : 'cover', style: { flex: 1 }, zOrder: 0, streamURL: peerStream.toURL() })));
        }
        return (react_1.default.createElement(react_native_webrtc_1.RTCView
        // @ts-ignore
        , { 
            // @ts-ignore
            objectFit: contain ? 'contain' : 'cover', style: { flex: 1 }, mirror: peer.isMe ? shouldMirror() : false, streamURL: peerStream.toURL(), zOrder: 1 + zIndex }));
    };
    return (react_1.default.createElement(react_native_1.View, { style: [
            {
                backgroundColor: 'black',
                borderRadius: borderRadius_1.default.medium,
                borderColor: peer.id === activeSpeakerPeerId
                    ? colors.primary[500]
                    : colors.secondary[900],
                borderWidth: 2,
                width: width - 8,
                height: height - 8,
                margin: 3,
                overflow: 'hidden',
            },
        ] },
        peer.videoVisible && screenshareHack ? (renderVideo()) : (react_1.default.createElement(components_1.Flex, { bg: colors.videoBackground, width: width - 8, height: height - 8, justify: "center", align: "center" },
            react_1.default.createElement(react_native_user_avatar_1.default, { size: 40, src: peer.picture, name: `${peer.displayName.replace(/[^\w\s]/gi, '')}`, bgColor: colors.primary[700] }))),
        children,
        react_1.default.createElement(components_1.Flex, { width: width, position: "absolute", bottom: "10", left: 10 }, hideBadge || (react_1.default.createElement(components_1.Flex, { justify: "flex-start", alignSelf: "flex-start", direction: "column" }, !!self && (react_1.default.createElement(NameTag_1.default, { audioMuted: audioMuted, audioTrack: peer.audioTrack, name: self, size: isMobile || size === 'sm' ? 'sm' : 'md', screenshare: peer.screenshare }))))),
        react_1.default.createElement(components_1.Flex, { width: width, position: "absolute", top: "10", right: "10" }, videoScore < 10 && (react_1.default.createElement(components_1.Box, { zIndex: 5, justify: "flex-end", alignSelf: "flex-end", direction: "column" },
            react_1.default.createElement(VideoStrengthIndicator_1.default, { videoScore: videoScore })))),
        peer.screenshare &&
            (forced || !isLandscape) &&
            react_native_1.Platform.OS === 'android' &&
            meeting.setupConfig.clientId !==
                'd3e435fb-4d39-47b6-943a-c8f10d0dffe3' && (react_1.default.createElement(components_1.Flex, { width: width, position: "absolute", top: "10", right: 10 },
            react_1.default.createElement(components_1.Flex, { justify: "flex-start", alignSelf: isLandscape ? 'flex-start' : 'flex-end', direction: "column" },
                react_1.default.createElement(components_1.Button, { onClick: toggleOrientation },
                    react_1.default.createElement(components_1.VStack, { width: 36, p: "2", ml: 22, height: "36px", bg: "secondary.800", borderRadius: borderRadius_1.default.medium, align: "center", justify: "center" },
                        react_1.default.createElement(components_1.Text, { fontSize: "xs" },
                            react_1.default.createElement(components_1.Icon, { name: forced
                                    ? 'fullscreen-exit'
                                    : 'fullscreen', fill: forced
                                    ? colors.danger[500]
                                    : colors.textPrimary[100] })))))))));
}
exports.default = PeerView;
PeerView.defaultProps = {
    isMobile: false,
    hideBadge: false,
    height: 0,
    width: 'inherit',
    children: null,
    contain: false,
    totalPeers: 0,
    size: 'md',
    isMe: false,
    index: 1,
    zIndex: 0,
};
//# sourceMappingURL=PeerView.js.map