/*
 * Copyright (c) 2004-2017, by Alex Leigh.
 * All rights reserved.
 *
 * THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE
 * The copyright notice above does not evidence any
 * actual or intended publication of such source code.
 */

package lc.mecha.fabric;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.LinkedList;

/**
 * Implements a subscription base where all subscribers to a symbol will receive all messages for a symbol. The order
 * in which subscriptions will receive messages is not guaranteed.
 * <p>
 * MTS: Limited.
 *
 * @param <E> The message class.
 * @author Alex Leigh
 */
public class TopicSubscriptionBase<E> implements SubscriptionBase<E> {
    private static final Logger logger = LoggerFactory.getLogger(TopicSubscriptionBase.class);
    private final LinkedList<MessageSubscription<E>> subs = new LinkedList<>();

    @Override
    public void subscribe(final MessageSubscription<E> subscription) {
        logger.debug("subscribe(): {}", subscription);
        if (subs.contains(subscription)) {
            logger.error("subscribe() called but subscription already exists: {}", subscription);
            return;
        }
        subs.add(subscription);
    }

    @Override
    public String toString() {
        return "TopicSubscriptionBase{" +
                "subs=" + subs +
                '}';
    }

    /**
     * Remove a subscription from this fabric.
     *
     * @param subscription
     */
    @Override
    public void unsubscribe(final MessageSubscription<E> subscription) {
        subs.remove(subscription);
    }

    @Override
    /**
     * Return an iterator for all the subscriptions found within this subscription base who are interested
     * in the given symbol. The order is not guaranteed.
     */
    public Iterable<MessageSubscription<E>> matching(final String symbol) {
        return () -> new MatchingIterator<>(subs.iterator(), symbol);
    }
}