import React from "react";
import { WebSocketEventNames } from "./useWebSocket";

type Param = {
    listener?: (typeof WebSocketEventNames)[number];
};

/**
 * # Use Websocket Data Event Handler Hook
 */
export default function useWebSocketEventHandler<
    T extends { [key: string]: any } = { [key: string]: any }
>(param?: Param) {
    const [data, setData] = React.useState<T | undefined>(undefined);
    const [message, setMessage] = React.useState<string | undefined>(undefined);

    React.useEffect(() => {
        const dataEventListenerCallback = (e: Event) => {
            const customEvent = e as CustomEvent;
            const data = customEvent.detail.data as T | undefined;
            const __msg = customEvent.detail.message as string | undefined;

            if (data) setData(data);
            if (__msg && typeof __msg == "string") setMessage(__msg);
        };

        const messageEventName: (typeof WebSocketEventNames)[number] =
            param?.listener || "wsDataEvent";
        window.addEventListener(messageEventName, dataEventListenerCallback);

        return function () {
            window.removeEventListener(
                messageEventName,
                dataEventListenerCallback
            );
        };
    }, []);

    return { data, message };
}
