import type { Log } from "~/requests/logs";

export class LogRepo
{
    websocket?: WebSocket = undefined;

    listen(namespace: string, name: string, onReceive: (logs: Log[]) => void)
    {
        const websocket = new WebSocket(StringUtils.format("ws://%s/api/logs/%s/%s", useRuntimeConfig().public.apiWsBase, namespace, name));
        websocket.addEventListener('open', () => {
            console.info("Opened Websocket.");
        })
        websocket.addEventListener("message", (event) => {
            console.log(event.data);
            onReceive(JSON.parse(event.data) as Log[]);
        });
        const interval = setInterval(() => {
            console.info("[PING]");
            websocket.send('[PING]');
        }, 5000);
        websocket.addEventListener("close", () => {
            console.info("Closing websocket.");
            clearTimeout(interval);
        });
        this.websocket = websocket;
    }

    clear()
    {
        if (this.websocket)
        {
            this.websocket.close();
        }
    }
}