import React, { createContext, useState, useEffect } from 'react';
import io from 'socket.io-client';
import { useDispatch, useSelector } from 'react-redux';
import { EventEmitter } from 'events';
import { setRoomSocketState, RoomSocketState } from '../store/roomSlice';
import { CLIENT_APP_VERSION } from '../utils/config';
export const WebSocketContext = createContext(null);
export const WebSocketProvider = ({ children, url, roomURL, peerId, }) => {
    const dispatch = useDispatch();
    const [ws, setWS] = useState();
    const authToken = useSelector((state) => state.participant.authToken);
    useEffect(() => {
        if (!url || !roomURL || !peerId) {
            return () => { };
        }
        const emitter = new EventEmitter();
        const newSocket = io(`${url}?roomURL=${roomURL}&peerId=${peerId}&authToken=${authToken}&version=${CLIENT_APP_VERSION}`);
        newSocket.on('disconnect', () => {
            dispatch(setRoomSocketState(RoomSocketState.DISCONNECTED));
        });
        newSocket.on('connect_error', (e) => {
            console.log('connect_error', e);
        });
        newSocket.on('error', (err) => {
            console.log('err socket');
            if (err === 'roomNotFound') {
                // history.go(0);
                // Redirect back to session page
            }
        });
        newSocket.on('connect', () => {
            console.log('[DYTE] Connected');
            dispatch(setRoomSocketState(RoomSocketState.CONNECTED));
        });
        newSocket.on('event://server-simple-message', (message, callback) => {
            const parsedMessage = JSON.parse(message);
            emitter.emit('socket', parsedMessage, callback);
            dispatch(parsedMessage);
        });
        const sendMessage = (message, callBack) => new Promise((resolve) => {
            newSocket.emit('event://send-message', JSON.stringify(message), (response) => {
                const parsedMessage = JSON.parse(response);
                dispatch(parsedMessage);
                resolve(parsedMessage);
                if (callBack) {
                    callBack(parsedMessage);
                }
            });
        });
        setWS({
            socket: newSocket,
            sendMessage,
            emitter,
        });
        return () => {
            newSocket.disconnect();
            setWS(null);
        };
    }, [url, roomURL, peerId, authToken, dispatch]);
    return (<WebSocketContext.Provider value={ws}>
			{children}
		</WebSocketContext.Provider>);
};
//# sourceMappingURL=MediaRoomSocketService.js.map