/* eslint-disable no-underscore-dangle */
import React, { createContext, useContext, useState, useEffect, } from 'react';
import { useSelector } from 'react-redux';
import { MediaRoomContext } from '../services/MediaRoomService';
import { ConfigServiceContext } from '../utils/ConfigProvider';
import { UserTrackContext } from '../services/UserTrackProvider';
import { getScreenShare } from '../utils/media-utils';
import { MediaStates } from '../store/roomSlice';
import { DyteViewTypes } from '../utils/dyte-utils/src';
import { RequestToJoinType } from '../store/participantSlice';
export const PeersServiceContext = createContext(null);
export const PeersProvider = ({ children, }) => {
    const { meeting } = useContext(ConfigServiceContext);
    const [peersSave, setPeers] = useState([]);
    const peers = useSelector((state) => state.peers.joinedPeers);
    const self = useSelector((state) => state.participant);
    const consumers = useSelector((state) => state.consumers.activeConsumers);
    const screenshareVideoConsumer = consumers.find((c) => c.kind === 'video' && c.appData.screenShare);
    const screenshareAudioConsumer = consumers.find((c) => c.kind === 'audio' && c.appData.screenShare);
    const pinnedPeerId = useSelector((state) => state.room.pinnedPeerId);
    const roomViewType = useSelector((state) => state.room.roomViewType);
    const [selfPeer, setSelfPeer] = useState(null);
    const [screenSharePeer, setScreenSharePeer] = useState(null);
    const { mediaRoom, } = useContext(MediaRoomContext);
    const { mediaTracks: { screenShareVideoTrack, setScreenShareVideoTrack, screenShareAudioTrack, setScreenShareAudioTrack, }, inputDevices: { toggleAudioState, toggleVideoState, }, } = useContext(UserTrackContext);
    const participantHook = {
        pin: (peerId) => mediaRoom.pin(peerId),
        unpin: (peerId) => mediaRoom.pin(null),
        toggleSelfAudio: () => toggleAudioState(),
        toggleSelfVideo: () => toggleVideoState(),
        toggleSelfScreenSharing: async () => {
            if (!self.sharingScreen && !screenshareVideoConsumer) {
                if (screenShareVideoTrack !== undefined) {
                    screenShareVideoTrack.stop();
                }
                try {
                    const tracks = await getScreenShare();
                    setScreenShareVideoTrack(tracks.video);
                    setScreenShareAudioTrack(tracks.video);
                    mediaRoom.shareScreen(tracks);
                }
                catch (error) {
                    if (error?.message !== 'NotAllowedError') {
                        console.error(error);
                    }
                }
            }
            else {
                mediaRoom.disableScreenShare();
                setScreenShareVideoTrack(undefined);
                setScreenShareAudioTrack(undefined);
            }
        },
        disablePeerAudio: (peerId) => mediaRoom.disableAudio(peerId),
        disablePeerVideo: (peerId) => mediaRoom.disableVideo(peerId),
    };
    let allMuted = true;
    useEffect(() => {
        setSelfPeer({
            id: mediaRoom?.peerid,
            audioMuted: self.audioMuted,
            displayName: self.displayName,
            userId: self.id,
            picture: self.displayImageURL,
            isMe: true,
            isHost: self.isHost,
            videoVisible: !self.videoOff,
            videoTrack: mediaRoom?.webCamProducer?.track,
            audioTrack: mediaRoom?.micProducer?.track,
            isPinned: pinnedPeerId === mediaRoom?.peerid,
            clientSpecificId: self.clientSpecificId,
            producingAudio: !self.audioMuted,
            producingVideo: !self.videoOff,
            isScreensharing: self.sharingScreen,
            requestToJoinType: self.requestToJoinType,
            hiddenParticipant: self.hidden,
            webinarHiddenParticipant: self.webinarHiddenParticipant
        });
    }, [
        mediaRoom?.peerid,
        self.sharingScreen,
        self.videoOff,
        self.audioMuted,
        self.displayName,
        self.hidden,
        self.requestToJoinType,
        mediaRoom?.webCamProducer?.track,
        mediaRoom?.micProducer?.track,
        self.webinarHiddenParticipant,
        pinnedPeerId
    ]);
    useEffect(() => {
        if (selfPeer && meeting) {
            meeting._addUpdateParticipant({
                ...selfPeer,
                isPinned: selfPeer.id === pinnedPeerId,
                isScreensharing: self.sharingScreen,
            }, participantHook);
        }
    }, [selfPeer, meeting]);
    useEffect(() => {
        if (screenshareVideoConsumer || self.screenSharingProduction === MediaStates.LOADED) {
            const videoTrack = screenshareVideoConsumer
                ? mediaRoom.consumers.get(screenshareVideoConsumer.id)?.track
                : mediaRoom.screenShareVideoProducer?.track;
            const audioTrack = screenshareAudioConsumer
                ? mediaRoom.consumers.get(screenshareAudioConsumer.id)?.track : null;
            const screensharePeer = screenshareVideoConsumer
                ? peers.find((p) => p.id === screenshareVideoConsumer.appData.peerId)
                : selfPeer;
            setScreenSharePeer({
                videoTrack,
                id: screensharePeer?.id,
                displayName: `Screen - ${screensharePeer?.displayName}`,
                videoVisible: true,
                audioTrack,
                audioMuted: audioTrack === null,
                screenshare: true,
            });
        }
        else {
            setScreenSharePeer(null);
        }
    }, [screenshareVideoConsumer, self.screenSharingProduction]);
    useEffect(() => {
        if (meeting) {
            peersSave.map((p) => {
                if (!(peers.find((peer) => peer.id === p.id))) {
                    meeting._removeParticipant(p);
                }
                return null;
            });
            setPeers(peers);
        }
    }, [peers]);
    const processPeer = (peer) => {
        const processedPeer = {
            id: peer.id,
            displayName: peer.displayName,
            picture: peer.picture,
            device: peer.device,
            audioTrack: null,
            videoTrack: null,
            hiddenParticipant: peer.hiddenParticipant,
            isPinned: pinnedPeerId === peer.id,
            clientSpecificId: peer.clientSpecificId,
            webinarHiddenParticipant: peer.webinarHiddenParticipant,
            isScreensharing: false,
            requestToJoinType: peer.requestToJoinType,
        };
        const videoConsumer = consumers
            .find((c) => c.peerId === peer.id && c.kind === 'video' && !c.appData.screenShare);
        const audioConsumer = consumers
            .find((c) => c.peerId === peer.id && c.kind === 'audio' && !c.appData.screenShare);
        if (videoConsumer) {
            processedPeer.producingVideo = true;
            processedPeer.videoTrack = mediaRoom.consumers.get(videoConsumer.id).track;
            processedPeer.videoScore = videoConsumer.producerScore;
            // console.log(processedPeer,"s");
        }
        if (audioConsumer) {
            processedPeer.producingAudio = !peer.audioMuted;
            processedPeer.audioTrack = mediaRoom.consumers.get(audioConsumer.id).track;
            processedPeer.audioScore = audioConsumer.producerScore;
        }
        if (screenshareVideoConsumer?.appData?.peerId === peer.id) {
            processedPeer.isScreensharing = true;
        }
        processedPeer.videoVisible = !(videoConsumer === undefined || videoConsumer.remotelyPaused);
        processedPeer.audioMuted = audioConsumer === undefined
            || audioConsumer.remotelyPaused || peer.audioMuted;
        if (!processedPeer.audioMuted)
            allMuted = false;
        if (meeting) {
            meeting._addUpdateParticipant({
                ...processedPeer, isPinned: processedPeer.id === pinnedPeerId,
            }, participantHook);
        }
        return processedPeer;
    };
    const getProcessedPeers = () => {
        let allPeers;
        if (roomViewType === DyteViewTypes.webinar) {
            allPeers = peers.filter((p) => !p?.webinarHiddenParticipant && p.requestToJoinType !== RequestToJoinType.ask).map(processPeer).filter((p) => p !== null);
            return allPeers;
        }
        allPeers = peers.filter((p) => !p?.hiddenParticipant).map(processPeer).filter((p) => p !== null);
        return allPeers;
    };
    const processedPeers = getProcessedPeers();
    const joinedProcessedPeers = peers.map(processPeer).filter((p) => p !== null);
    return (<PeersServiceContext.Provider value={{
        processedPeers,
        selfPeer,
        allMuted,
        screenshareVideoConsumer,
        screenshareAudioConsumer,
        screenSharePeer,
        joinedProcessedPeers
    }}>
			{children}
		</PeersServiceContext.Provider>);
};
//# sourceMappingURL=PeersService.js.map