package eu.dnetlib.enabling.tools.blackboard;

import java.util.HashMap;
import java.util.Map;

/**
 * This notification handler dispatches incoming notifications to registered blackboard message listeners. Usually used
 * by blackboard notification clients, since they are usually interested only in the messages they have sent and not in
 * messages sent by other BB clients. Moreover it's an useful hook for dispatching orchestration.
 *
 * @param <T>
 *            blackboard handler (client or server)
 * @author marko
 *
 */
public class BlackboardNotificationHandler<T extends BlackboardHandler> extends AbstractBlackboardNotificationHandler<T> implements BlackboardJobRegistry {

	/**
	 * blackboard message listeners.
	 */
	private Map<String, BlackboardJobListener> listeners = new HashMap<String, BlackboardJobListener>();

	/**
	 * {@inheritDoc}
	 *
	 * @see eu.dnetlib.enabling.tools.blackboard.AbstractBlackboardNotificationHandler#processJob(eu.dnetlib.enabling.tools.blackboard.BlackboardJob)
	 */
	@Override
	protected void processJob(final BlackboardJob job) {
		final BlackboardJobListener listener = listeners.get(job.getId());
		if (listener != null) {
			if (job.isCompleted()) {
				listeners.remove(job.getId());
			}

			listener.processJob(job);
		}
	}

	/**
	 * {@inheritDoc}
	 *
	 * @see eu.dnetlib.enabling.tools.blackboard.BlackboardJobRegistry#registerJobListener(eu.dnetlib.enabling.tools.blackboard.BlackboardJob,
	 *      eu.dnetlib.enabling.tools.blackboard.BlackboardJobListener)
	 */
	@Override
	public void registerJobListener(final BlackboardJob job, final BlackboardJobListener listener) {
		listeners.put(job.getId(), listener);
	}

	public Map<String, BlackboardJobListener> getListeners() {
		return listeners;
	}

	public void setListeners(final Map<String, BlackboardJobListener> listeners) {
		this.listeners = listeners;
	}

}
