"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 __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.PeersProvider = exports.PeersServiceContext = void 0;
/* eslint-disable no-underscore-dangle */
const react_1 = __importStar(require("react"));
const react_redux_1 = require("react-redux");
const peersSlice_1 = require("../store/peersSlice");
const MediaRoomService_1 = require("./MediaRoomService");
const ConfigProvider_1 = require("../utils/ConfigProvider");
const UserTrackProvider_1 = require("./UserTrackProvider");
const media_utils_1 = require("../utils/media-utils");
const roomSlice_1 = require("../store/roomSlice");
const src_1 = require("../utils/dyte-utils/src");
const participantSlice_1 = require("../store/participantSlice");
exports.PeersServiceContext = react_1.createContext(null);
const PeersProvider = ({ children, }) => {
    var _a, _b;
    const { meeting } = react_1.useContext(ConfigProvider_1.ConfigServiceContext);
    const [peersSave, setPeers] = react_1.useState([]);
    const peers = react_redux_1.useSelector((state) => state.peers.joinedPeers);
    const self = react_redux_1.useSelector((state) => state.participant);
    const consumers = react_redux_1.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 = react_redux_1.useSelector((state) => state.room.pinnedPeerId);
    const roomViewType = react_redux_1.useSelector((state) => state.room.roomViewType);
    const [selfPeer, setSelfPeer] = react_1.useState(null);
    const [screenSharePeer, setScreenSharePeer] = react_1.useState(null);
    const { mediaRoom } = react_1.useContext(MediaRoomService_1.MediaRoomContext);
    const dispatch = react_redux_1.useDispatch();
    const { mediaTracks: { screenShareVideoTrack, setScreenShareVideoTrack, screenShareAudioTrack, setScreenShareAudioTrack, }, inputDevices: { toggleAudioState, toggleVideoState }, } = react_1.useContext(UserTrackProvider_1.UserTrackContext);
    const participantHook = {
        pin: (peerId) => mediaRoom.pin(peerId),
        unpin: (peerId) => mediaRoom.pin(null),
        toggleSelfAudio: () => toggleAudioState(),
        toggleSelfVideo: () => toggleVideoState(),
        toggleSelfScreenSharing: () => __awaiter(void 0, void 0, void 0, function* () {
            if (!self.sharingScreen && !screenshareVideoConsumer) {
                if (screenShareVideoTrack !== undefined) {
                    screenShareVideoTrack.stop();
                }
                try {
                    const tracks = yield media_utils_1.getScreenShare();
                    setScreenShareVideoTrack(tracks.video);
                    setScreenShareAudioTrack(tracks.video);
                    mediaRoom.shareScreen(tracks);
                }
                catch (error) {
                    if ((error === null || error === void 0 ? void 0 : error.message) !== 'NotAllowedError') {
                        console.error(error);
                    }
                }
            }
            else {
                mediaRoom.disableScreenShare();
                setScreenShareVideoTrack(undefined);
                setScreenShareAudioTrack(undefined);
            }
        }),
        disablePeerAudio: (peerId) => mediaRoom.disableAudio(peerId),
        disablePeerVideo: (peerId) => mediaRoom.disableVideo(peerId),
        updatePreset: (id, presetName) => mediaRoom.updatePreset(id, presetName),
        setLabel: (id, label) => {
            dispatch(peersSlice_1.setPeerLabel({ id, label }));
        },
    };
    let allMuted = true;
    react_1.useEffect(() => {
        var _a, _b;
        setSelfPeer({
            id: mediaRoom === null || mediaRoom === void 0 ? void 0 : mediaRoom.peerid,
            audioMuted: self.audioMuted,
            displayName: self.displayName,
            userId: self.id,
            picture: self.displayImageURL,
            isMe: true,
            isHost: self.isHost,
            videoVisible: !self.videoOff,
            videoTrack: (_a = mediaRoom === null || mediaRoom === void 0 ? void 0 : mediaRoom.webCamProducer) === null || _a === void 0 ? void 0 : _a.track,
            audioTrack: (_b = mediaRoom === null || mediaRoom === void 0 ? void 0 : mediaRoom.micProducer) === null || _b === void 0 ? void 0 : _b.track,
            isPinned: pinnedPeerId === (mediaRoom === null || mediaRoom === void 0 ? void 0 : mediaRoom.peerid),
            clientSpecificId: self.clientSpecificId,
            producingAudio: !self.audioMuted,
            producingVideo: !self.videoOff,
            isScreensharing: self.sharingScreen,
            requestToJoinType: self.requestToJoinType,
            hiddenParticipant: self.hidden,
            webinarHiddenParticipant: self.webinarHiddenParticipant,
            metadata: self.metadata,
        });
    }, [
        mediaRoom === null || mediaRoom === void 0 ? void 0 : mediaRoom.peerid,
        self.sharingScreen,
        self.videoOff,
        self.audioMuted,
        self.displayName,
        self.hidden,
        self.requestToJoinType,
        self.metadata,
        (_a = mediaRoom === null || mediaRoom === void 0 ? void 0 : mediaRoom.webCamProducer) === null || _a === void 0 ? void 0 : _a.track,
        (_b = mediaRoom === null || mediaRoom === void 0 ? void 0 : mediaRoom.micProducer) === null || _b === void 0 ? void 0 : _b.track,
        self.webinarHiddenParticipant,
        pinnedPeerId,
    ]);
    react_1.useEffect(() => {
        if (selfPeer && meeting) {
            meeting._addUpdateParticipant(Object.assign(Object.assign({}, selfPeer), { isPinned: selfPeer.id === pinnedPeerId, isScreensharing: self.sharingScreen }), participantHook);
        }
    }, [selfPeer, meeting]);
    react_1.useEffect(() => {
        var _a, _b, _c;
        if (screenshareVideoConsumer ||
            self.screenSharingProduction === roomSlice_1.MediaStates.LOADED) {
            const videoTrack = screenshareVideoConsumer
                ? (_a = mediaRoom.consumers.get(screenshareVideoConsumer.id)) === null || _a === void 0 ? void 0 : _a.track : (_b = mediaRoom.screenShareVideoProducer) === null || _b === void 0 ? void 0 : _b.track;
            const audioTrack = screenshareAudioConsumer
                ? (_c = mediaRoom.consumers.get(screenshareAudioConsumer.id)) === null || _c === void 0 ? void 0 : _c.track : null;
            const screensharePeer = screenshareVideoConsumer
                ? peers.find((p) => p.id === screenshareVideoConsumer.appData.peerId)
                : selfPeer;
            setScreenSharePeer({
                videoTrack,
                id: screensharePeer === null || screensharePeer === void 0 ? void 0 : screensharePeer.id,
                displayName: `Screen - ${screensharePeer === null || screensharePeer === void 0 ? void 0 : screensharePeer.displayName}`,
                videoVisible: true,
                audioTrack,
                audioMuted: audioTrack === null,
                screenshare: true,
            });
        }
        else {
            setScreenSharePeer(null);
        }
    }, [screenshareVideoConsumer, self.screenSharingProduction]);
    react_1.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) => {
        var _a;
        const processedPeer = Object.assign(Object.assign({}, peer), { isPinned: pinnedPeerId === peer.id, isScreensharing: false });
        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 (((_a = screenshareVideoConsumer === null || screenshareVideoConsumer === void 0 ? void 0 : screenshareVideoConsumer.appData) === null || _a === void 0 ? void 0 : _a.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(Object.assign(Object.assign({}, processedPeer), { isPinned: processedPeer.id === pinnedPeerId }), participantHook);
        }
        return processedPeer;
    };
    const getProcessedPeers = () => {
        let allPeers;
        if (roomViewType === src_1.DyteViewTypes.webinar) {
            allPeers = peers
                .filter((p) => !(p === null || p === void 0 ? void 0 : p.webinarHiddenParticipant) &&
                p.requestToJoinType !== participantSlice_1.RequestToJoinType.ask)
                .map(processPeer)
                .filter((p) => p !== null);
            return allPeers;
        }
        allPeers = peers
            .filter((p) => !(p === null || p === void 0 ? void 0 : p.hiddenParticipant))
            .map(processPeer)
            .filter((p) => p !== null);
        return allPeers;
    };
    const processedPeers = getProcessedPeers();
    const joinedProcessedPeers = peers
        .map(processPeer)
        .filter((p) => p !== null);
    return (react_1.default.createElement(exports.PeersServiceContext.Provider, { value: {
            processedPeers,
            selfPeer,
            allMuted,
            screenshareVideoConsumer,
            screenshareAudioConsumer,
            screenSharePeer,
            joinedProcessedPeers,
        } }, children));
};
exports.PeersProvider = PeersProvider;
//# sourceMappingURL=PeersService.js.map