const { makeSubscriber } = require('./connection');


async function listen (addChannels, callback) {

	const client = makeSubscriber();

	client.events.on("error", (err) => {
		console.error("Postgres LISTEN subscriber error", err);
		setTimeout(() => client.connect(), 5000);
	});

	client.connect();

	if (!Array.isArray(addChannels)) {
		addChannels = [addChannels];
	}

	for (const channel of addChannels) {
		await client.listenTo(channel);
		client.notifications.on(channel, (payload) => {
			const data = {
				channel,
				_received: new Date(),
				payload
			};
			callback(data);
		});
	}

	return client;
}

module.exports = {
	listen
};
