// useGlobalEvents.ts
import { useEffect } from "react";
import { Events } from "@wailsio/runtime";
import { toast } from "react-toastify";

export function useGlobalEvents({
    setGameRunning,
    setServerRunning,
    setProxyRunning,
    setProgressUpdate,
    setMaxProgressUpdate,
    setProgressDownload,
    setDownloadSpeed,
    setMessageUpdate,
    setStageType,

}: {
    setGameRunning: (v: boolean) => void;
    setServerRunning: (v: boolean) => void;
    setProxyRunning: (v: boolean) => void;
    setProgressUpdate: (v: number) => void;
    setMaxProgressUpdate: (v: number) => void;
    setProgressDownload: (v: number) => void;
    setDownloadSpeed: (v: number) => void;
    setMessageUpdate: (v: string) => void;
    setStageType: (v: string) => void,
}) {
    useEffect(() => {
        const onGameExit = () => setGameRunning(false);
        const onServerExit = () => setServerRunning(false);
        const onProxyExit = () => setProxyRunning(false);

        const onDownload = (event: any) => {
            const { percent, speed } = event.data[0];
            setProgressDownload(Number(percent));
            setDownloadSpeed(Number(speed));
        };

        const onUpdateProgress = (event: any) => {
            const { progress, maxProgress } = event.data[0];
            setProgressUpdate(Number(progress));
            setMaxProgressUpdate(Number(maxProgress));
        };

        const onMessageUpdate = (event: any) => {
            const { message } = event.data[0];
            setMessageUpdate(message);
        };

        const onStageUpdate = (event: any) => {
            const { stage } = event.data[0];
            setStageType(stage);
        };

        Events.On("download:server", onDownload);
        Events.On("download:proxy", onDownload);
        Events.On("game:exit", onGameExit);
        Events.On("server:exit", onServerExit);
        Events.On("proxy:exit", onProxyExit);
        Events.On("diff:progress", onUpdateProgress);
        Events.On("diff:message", onMessageUpdate);
        Events.On("diff:stage", onStageUpdate);
        Events.On("diff:error", (event: any) => {
            const { message } = event.data[0];
            toast.error(message);
        });

        return () => {
            Events.Off("download:server");
            Events.Off("download:proxy");
            Events.Off("game:exit");
            Events.Off("server:exit");
            Events.Off("proxy:exit");
            Events.Off("diff:progress")
            Events.Off("diff:message");
            Events.Off("diff:stage");
            Events.Off("version:check");
        };
    }, []);
}
