package eu.dnetlib.broker.events.output;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import eu.dnetlib.broker.common.elasticsearch.Event;
import eu.dnetlib.broker.common.subscriptions.Subscription;

@Component
public class DispatcherManager {

	@Autowired(required = false)
	private final List<NotificationDispatcher> dispatchers = new ArrayList<>();

	private static final Log log = LogFactory.getLog(DispatcherManager.class);

	public void dispatch(final Subscription s, final Event... events) {
		final Optional<NotificationDispatcher> dispatcher = this.dispatchers
			.stream()
			.filter(d -> d.getMode() == s.getMode())
			.findFirst();

		if (dispatcher.isPresent()) {
			dispatcher.get().sendNotification(s, events);
		} else {
			log.error("Notification dispatcher not found, mode=" + s.getMode());
		}
	}

	public void sendNotification(final Subscription s, final Map<String, Object> params) {
		final Optional<NotificationDispatcher> dispatcher = this.dispatchers
			.stream()
			.filter(d -> d.getMode() == s.getMode())
			.findFirst();

		if (dispatcher.isPresent()) {
			dispatcher.get().sendNotification(s, params);
		} else {
			log.error("Notification dispatcher not found, mode=" + s.getMode());
		}
	}

	public List<NotificationDispatcher> getDispatchers() {
		return this.dispatchers;
	}

}
