'use strict';

class HighlightFeedItemHandler {
    constructor() {
        this.feeds = [];
        this.containsFeedItem = (itemId) => (feed) => {
            return feed.items.some((item) => item.id === itemId);
        };
    }
    handle(command) {
        const feeds = this.feeds
            .filter((feed) => feed.isConnected)
            .filter(this.containsFeedItem(command.itemId));
        if (feeds.length === 0) {
            throw new Error(`No feed found containing item with id: ${command.itemId}`);
        }
        for (const feed of feeds) {
            if (feed.highlightedItemId === command.itemId) {
                feed.highlightedItemId = undefined;
            }
            feed.highlightedItemId = command.itemId;
        }
    }
    registerFeed(feed) {
        if (!this.feeds.includes(feed)) {
            this.feeds.push(feed);
        }
    }
    unregisterFeed(feed) {
        const index = this.feeds.indexOf(feed);
        if (index !== -1) {
            this.feeds.splice(index, 1);
        }
    }
}
HighlightFeedItemHandler.SERVICE_NAME = 'feed.highlight-item';

exports.HighlightFeedItemHandler = HighlightFeedItemHandler;
