"use strict";

const syncpipe = require("syncpipe");
const flatten = require("flatten");

module.exports = function mapEvents(events, eventMapper) {
	// TODO: Do we need to deduplicate mapped events here?
	return syncpipe(events, [
		(_) => _.map((event) => {
			// FIXME: Remove
			// console.log(require("util").inspect(event, { colors: require("supports-color").stderr, depth: null }));
			
			if (event.event != null) {
				let mappedEvents = (eventMapper != null)
					? eventMapper(event.event, event.type)
					: event.event;

				if (Array.isArray(mappedEvents)) {
					if (mappedEvents.length > 0) {
						return mappedEvents.map((mappedEvent) => {
							// TODO: Could mutability provide a significant performance improvement here? (also in stream-backlog)
							return {
								... event,
								protocolEvent: event.event,
								event: mappedEvent
							};
						});
					} else {
						return null;
					}
				} else if (mappedEvents != null) {
					return {
						... event,
						protocolEvent: event.event,
						event: mappedEvents
					};
				} else {
					return null;
				}
			} else {
				return event;
			}
		}),
		(_) => _.filter((event) => event != null),
		(_) => flatten(_)
	]);
};
