var GnsEventSource = {
    eventSource: null,
    addEvents: (events, callback) => {
        events.forEach((element) => {
            GnsEventSource.addEvent(element, callback);
        })
    },
    start: (url, onConnect = () => {}) => {
        GnsEventSource.stop()
        GnsEventSource.eventSource = new EventSource(url)
        GnsEventSource.eventSource.onopen = () => {
            onConnect()
        }
        GnsEventSource.eventSource.onerror = () => {
            console.error('SSE connection closed');
        }
    },
    addEvent: (event, action) => {
        if (GnsEventSource.eventSource) {
            GnsEventSource.eventSource.addEventListener(event, action)
        }
    },
    removeEvent: (event, action) => {
        if (GnsEventSource.eventSource) {
            GnsEventSource.eventSource.removeEventListener(event, action)
        }
    },
    stop: () => {
        if (GnsEventSource.eventSource && GnsEventSource.eventSource.close) {
            GnsEventSource.eventSource.close()
            GnsEventSource.eventSource = null
        }
    }
}
