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

export class LogRepo
{
    websocket?: WebSocket = undefined;

    listen(resourceType: string, namespace: string, name: string, onReceive: (logs: Log[]) => void)
    {
        const websocket = new WebSocket(StringUtils.format("%s/logs/%s/%s/%s", ApiConfig.getWsBase(), resourceType, namespace, name));
        websocket.addEventListener('open', () => {
            console.info("Opened Websocket.");
        })
        websocket.addEventListener("message", (event) => {
            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();
        }
    }
}