"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useLivestreamWebsocket = useLivestreamWebsocket;
const tslib_1 = require("tslib");
const react_1 = require("react");
const react_use_websocket_1 = tslib_1.__importDefault(require("react-use-websocket"));
const livestream_store_1 = require("../livestream-store");
const streamplace_store_1 = require("../streamplace-store");
function useLivestreamWebsocket(src) {
    const url = (0, streamplace_store_1.useUrl)();
    const handleWebSocketMessages = (0, livestream_store_1.useHandleWebsocketMessages)();
    let wsUrl = url.replace(/^http\:/, "ws:");
    wsUrl = wsUrl.replace(/^https\:/, "wss:");
    const ref = (0, react_1.useRef)([]);
    const handle = (0, react_1.useRef)(null);
    const hasReceivedMessage = (0, react_1.useRef)(false);
    const hasErrored = (0, react_1.useRef)(false);
    const { readyState } = (0, react_use_websocket_1.default)(`${wsUrl}/api/websocket/${src}`, {
        reconnectInterval: 1000,
        shouldReconnect: () => !hasErrored.current,
        onOpen: () => {
            ref.current = [];
            hasReceivedMessage.current = false;
        },
        onError: (e) => {
            console.log("onError", e);
            if (!hasReceivedMessage.current) {
                hasErrored.current = true;
                handleWebSocketMessages([
                    {
                        $type: "place.stream.error",
                        code: "user_not_found",
                        message: "this stream doesn't exist or is unavailable",
                    },
                ]);
            }
        },
        // spamming the redux store with messages causes a zillion re-renders,
        // so we batch them up a bit
        onMessage: (msg) => {
            try {
                const data = JSON.parse(msg.data);
                hasReceivedMessage.current = true;
                ref.current.push(data);
                if (handle.current) {
                    return;
                }
                handle.current = setTimeout(() => {
                    handleWebSocketMessages(ref.current);
                    ref.current = [];
                    handle.current = null;
                }, 250);
            }
            catch (e) {
                console.log("onMessage parse error", e);
            }
        },
    });
}
//# sourceMappingURL=websocket.js.map