import onClose from "./events/on-close";
import onMessage from "./events/on-message";
import onOpen from "./events/on-open";
import { getRuntimeConfig, getRuntimeEden } from "../runtime.js";
import { cleanupSocketSideEffects } from "./events/on-close";
function toWebsocketEndpoint(edenApi) {
    if (edenApi.startsWith("https://")) {
        return `${edenApi.replace("https://", "wss://")}/ws`;
    }
    if (edenApi.startsWith("http://")) {
        return `${edenApi.replace("http://", "ws://")}/ws`;
    }
    return `${edenApi}/ws`;
}
export default function connectWebsocket() {
    const eden = getRuntimeEden();
    if (eden.socket &&
        (eden.socket.readyState === WebSocket.OPEN ||
            eden.socket.readyState === WebSocket.CONNECTING)) {
        return eden.socket;
    }
    const { edenApi } = getRuntimeConfig();
    const endpoint = toWebsocketEndpoint(edenApi);
    const socket = new WebSocket(endpoint);
    eden.socket = socket;
    socket.addEventListener("open", onOpen);
    socket.addEventListener("close", onClose);
    socket.addEventListener("message", onMessage);
    return socket;
}
export function disconnectWebsocket() {
    const eden = getRuntimeEden();
    const socket = eden.socket;
    if (!socket) {
        cleanupSocketSideEffects();
        return;
    }
    cleanupSocketSideEffects();
    socket.removeEventListener("open", onOpen);
    socket.removeEventListener("close", onClose);
    socket.removeEventListener("message", onMessage);
    if (socket.readyState === WebSocket.OPEN ||
        socket.readyState === WebSocket.CONNECTING) {
        socket.close();
    }
    eden.socket = undefined;
}
