"use strict";

const createEventEmitter = require("create-event-emitter");

let eventTypes = [
	"task:new",
	"task:progress",
	"task:completed"
];

module.exports = function createSseChannelClient() {
	if (window.EventSource != null) {
		let source = new EventSource("/event-stream");
		let emitter = createEventEmitter();

		eventTypes.forEach((type) => {
			source.addEventListener(type, (event) => {
				emitter.emit(type, JSON.parse(event.data));
			});
		});

		return emitter;
	} else {
		throw new Error("This browser does not support SSE; could not establish event stream.");
	}
};
