import React from "react";

type Param = {
    /**
     * Custom Event Name
     */
    name: string;
};

/**
 * # Listen For Custom Event
 */
export default function useCustomEventListener<
    T extends { [key: string]: any } = { [key: string]: any }
>({ name }: Param) {
    const [data, setData] = React.useState<T | undefined>(undefined);
    const [message, setMessage] = React.useState<string | undefined>(undefined);

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

        if (eventPayloadMessage) setMessage(eventPayloadMessage);
        if (eventPayloadData) setData(eventPayloadData);
    }, []);

    React.useEffect(() => {
        window.addEventListener(name, dataEventListenerCallback, false);

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

    return { data, message };
}
