package lc.mecha.mq;

import lc.mecha.log.MechaLogger;
import lc.mecha.log.MechaLoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * A trivial implementation of a fanout to independent queues.
 *
 * @param <T> The type of object the queues deal in.
 * @author Alex Leigh
 */
public class Fanout<T> {
    private static final MechaLogger logger = MechaLoggerFactory.getLogger(Fanout.class);
    private final List<Queue<T>> queues = new ArrayList<>();

    /**
     * Create a new queue and return it to the caller. The ID will be randomly generated.
     */
    public Queue<T> createQueue() {
        Queue<T> q = new Queue<>(UUID.randomUUID(), this);
        queues.add(q);
        return q;
    }

    /**
     * Write a message to all queues in this fanout.
     */
    public void write(T obj) {
        for (Queue<T> q : queues) {
            logger.info("Writing msg to queue. [q: {}]", q);
            try {
                q.write(obj);
            } catch (InterruptedException e) {
                // FIXME: Should remove bad queues.
                e.printStackTrace();
            }
        }
    }

    public void destroyQueue(Queue<T> q) {
        logger.info("Destroy queue called: {}", q);
        queues.remove(q);
    }
}
