"use strict";

const SseChannel = require("sse-channel");

module.exports = function createEventStream() {
	let channel = new SseChannel({
		jsonEncode: true
	});

	let messageId = 0;

	return {
		connectClient: function (request, response) {
			channel.addClient(request, response);
		},
		disconnectClient: function (response) {
			channel.send({
				id: messageId++,
				event: "disconnect"
			});

			channel.removeClient(response);
			response.end();
		},
		reportNewTask: function (task) {
			channel.send({
				id: messageId++,
				event: "task:new",
				data: {
					task: task
				}
			});
		},
		reportCompletedTask: function (taskId) {
			channel.send({
				id: messageId++,
				event: "task:completed",
				data: {
					id: taskId
				}
			});
		},
		reportTaskProgress: function (taskId, progress) {
			channel.send({
				id: messageId++,
				event: "task:progress",
				data: {
					id: taskId,
					progress: progress
				}
			});
		}
	};
};
