package eu.dnetlib.data.mdstore.modular.action;

import java.util.Map;

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

import eu.dnetlib.data.mdstore.MDStoreServiceException;
import eu.dnetlib.enabling.tools.blackboard.BlackboardJob;
import eu.dnetlib.enabling.tools.blackboard.BlackboardServerHandler;

public class PluginAction extends AbstractMDStoreAction {

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

	@Autowired
	private MDStorePluginEnumerator pluginEnumerator;

	@Override
	protected void executeAsync(final BlackboardServerHandler handler, final BlackboardJob job) throws MDStoreServiceException {

		final String name = job.getParameters().get("plugin.name");

		final Map<String, MDStorePlugin> plugins = pluginEnumerator.getAll();

		if ((plugins == null) || plugins.isEmpty() || !plugins.containsKey(name)) throw new MDStoreServiceException("Unable to find plugin: " + name);

		log.info("running MDStore plugin: " + name);

		plugins.get(name).run(getDao(), job.getParameters(), new DoneCallback() {

			@Override
			public void call(final Map<String, String> params) {
				job.getParameters().putAll(params);
				handler.done(job);
			}
		});
	}

}
