"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 });
exports.WebSocketProvider = exports.WebSocketContext = void 0;
const react_1 = __importStar(require("react"));
const socket_io_client_1 = __importDefault(require("socket.io-client"));
const react_redux_1 = require("react-redux");
const events_1 = require("events");
const roomSlice_1 = require("../store/roomSlice");
const config_1 = require("../utils/config");
exports.WebSocketContext = react_1.createContext(null);
const WebSocketProvider = ({ children, url, roomURL, peerId, }) => {
    const dispatch = react_redux_1.useDispatch();
    const [ws, setWS] = react_1.useState();
    const authToken = react_redux_1.useSelector((state) => state.participant.authToken);
    react_1.useEffect(() => {
        if (!url || !roomURL || !peerId) {
            return () => { };
        }
        const emitter = new events_1.EventEmitter();
        const newSocket = socket_io_client_1.default(`${url}?roomURL=${roomURL}&peerId=${peerId}&authToken=${authToken}&version=${config_1.CLIENT_APP_VERSION}`);
        newSocket.on('disconnect', () => {
            dispatch(roomSlice_1.setRoomSocketState(roomSlice_1.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(roomSlice_1.setRoomSocketState(roomSlice_1.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 (react_1.default.createElement(exports.WebSocketContext.Provider, { value: ws }, children));
};
exports.WebSocketProvider = WebSocketProvider;
//# sourceMappingURL=MediaRoomSocketService.js.map