import { MediaStates, setProducersState } from '../store/roomSlice';
import { MediaRoomContext } from '../services/MediaRoomService';
import { UserTrackContext } from '../services/UserTrackProvider';
import React, { useContext, useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { ConfigServiceContext } from '../utils/ConfigProvider';
const StageService = (props) => {
    const dispatch = useDispatch();
    const { processPreset } = useContext(ConfigServiceContext);
    const producersState = useSelector((state) => state.room.producersState);
    const legacyMode = useSelector((state) => state.room.legacyMode);
    const joined = useSelector((state) => state.room.joined);
    const dynPreset = useSelector((state) => state.participant.preset);
    const audioMuted = useSelector((state) => state.participant.audioMuted);
    const { mediaRoom, } = useContext(MediaRoomContext);
    const { mediaTracks: { audioTrack, webcamTrack, screenShareVideoTrack, }, } = useContext(UserTrackContext);
    useEffect(() => {
        const changeTrack = async () => {
            if (legacyMode !== mediaRoom.legacyMode) {
                mediaRoom.legacyMode = legacyMode;
                mediaRoom.resetVideoProducers(webcamTrack, screenShareVideoTrack);
            }
        };
        if (mediaRoom && producersState === MediaStates.LOADED) {
            changeTrack();
        }
    }, [legacyMode, producersState]);
    useEffect(() => {
        const startProducing = async () => {
            dispatch(setProducersState(MediaStates.CONNECTING));
            if (webcamTrack) {
                await mediaRoom.shareWebcam(webcamTrack);
            }
            if (audioTrack) {
                await mediaRoom.shareMic(audioTrack, audioMuted);
            }
            dispatch(setProducersState(MediaStates.LOADED));
        };
        const fetchData = () => {
            mediaRoom.getMesssages();
            mediaRoom.getPolls();
        };
        if (producersState === MediaStates.NOT_STARTED) {
            // Don't fetch data again for hidden state change
            if (!mediaRoom.hidden) {
                fetchData();
            }
            mediaRoom.hidden = false;
            startProducing();
        }
    }, [producersState, joined]);
    useEffect(() => {
        if (dynPreset) {
            processPreset(dynPreset);
        }
    }, [dynPreset]);
    return null;
};
export default React.memo(StageService);
//# sourceMappingURL=StageService.js.map