import { useCallback, useEffect, useRef, useState } from "react";

export const useWebsocket = (props: {url: string; onMessage: (stuff: {socket: WebSocket; message: unknown}) => void}) => {
    const {url, onMessage} = props;
    const onMessageRef = useRef(onMessage);
    const ws = useRef<WebSocket | null>(null);
    onMessageRef.current = onMessage;

    useEffect(() => {
        const webSocket = new WebSocket(url);

        webSocket.addEventListener("open", () => {
            console.log("WebSocket is open now.");
        });

        webSocket.addEventListener("message", (event: any) => {
            onMessageRef.current({socket: webSocket, message: JSON.parse(event.data)});
        });

		webSocket.addEventListener("error", (event) => {
            console.log("WebSocket error: ", event);
        });

        webSocket.addEventListener("close", () => {
            console.log("WebSocket is closed now.");
            ws.current = null;
        });

        ws.current = webSocket;

        return () => {
            webSocket.close();
        };

    }, [url]);

    const sendMessage = useCallback((message: unknown) => {
        if (ws.current && ws.current.readyState === WebSocket.OPEN) {
            ws.current.send(JSON.stringify(message));
        } else {
            console.error("WebSocket is not open. Message not sent.");
        }
    }, []);

    return {sendMessage};
};