package eu.dnetlib.msro.workflows.nodes.db;

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

import com.googlecode.sarasvati.NodeToken;

import eu.dnetlib.enabling.database.rmi.DatabaseService;
import eu.dnetlib.enabling.tools.blackboard.BlackboardJob;
import eu.dnetlib.msro.workflows.nodes.BlackboardJobNode;
import eu.dnetlib.msro.workflows.nodes.ProgressJobNode;
import eu.dnetlib.msro.workflows.resultset.ProcessCountingResultSetFactory;
import eu.dnetlib.msro.workflows.util.ProgressProvider;
import eu.dnetlib.msro.workflows.util.ResultsetProgressProvider;

public class UpdateDbJobNode extends BlackboardJobNode implements ProgressJobNode {

	private String db;
	private String dbParam;
	private String eprParam;
	private ProcessCountingResultSetFactory processCountingResultSetFactory;
	private ResultsetProgressProvider progressProvider;

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

	@Override
	protected String obtainServiceId(final NodeToken token) {
		return getServiceLocator().getServiceId(DatabaseService.class);
	}

	@Override
	protected void prepareJob(final BlackboardJob job, final NodeToken token) throws Exception {
		if (db == null || db.isEmpty()) {
			db = token.getEnv().getAttribute(getDbParam());
		}

		log.info("preparing blackboard job to update DB: " + db);

		final String epr = token.getEnv().getAttribute(getEprParam());

		this.progressProvider = processCountingResultSetFactory.createProgressProvider(token.getProcess(), epr);

		job.setAction("IMPORT");
		job.getParameters().put("db", db);
		job.getParameters().put("epr", this.progressProvider.getEpr().toString());
	}

	@Override
	public ProgressProvider getProgressProvider() {
		return progressProvider;
	}

	public String getDb() {
		return db;
	}

	public void setDb(final String db) {
		this.db = db;
	}

	public String getEprParam() {
		return eprParam;
	}

	public void setEprParam(final String eprParam) {
		this.eprParam = eprParam;
	}

	public ProcessCountingResultSetFactory getProcessCountingResultSetFactory() {
		return processCountingResultSetFactory;
	}

	@Required
	public void setProcessCountingResultSetFactory(final ProcessCountingResultSetFactory processCountingResultSetFactory) {
		this.processCountingResultSetFactory = processCountingResultSetFactory;
	}

	public String getDbParam() {
		return dbParam;
	}

	public void setDbParam(final String dbParam) {
		this.dbParam = dbParam;
	}

}
