"use strict";

const syncpipe = require("syncpipe");

// NOTE: This is a workaround for https://github.com/matrix-org/synapse/issues/1597

module.exports = function removeStateDuplication(events) {
	let seenTimelineEvents = syncpipe(events, [
		(_) => _.filter((event) => event.type === "roomTimelineEvent"),
		(_) => _.map((event) => event.event.event_id),
		(_) => _.filter((id) => id != null),
		(_) => new Set(_)
	]);

	return events.filter((event) => {
		let isStateEvent = event.type === "roomStateUpdate";
		let isDuplicatedState = isStateEvent && seenTimelineEvents.has(event.event.event_id);

		return !isDuplicatedState;
	});
};
