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

import javax.annotation.Resource;

import com.googlecode.sarasvati.Arc;
import com.googlecode.sarasvati.NodeToken;
import eu.dnetlib.enabling.database.rmi.DatabaseService;
import eu.dnetlib.enabling.locators.UniqueServiceLocator;
import eu.dnetlib.msro.workflows.nodes.AsyncJobNode;
import org.apache.commons.lang.StringUtils;

public class ExecuteSqlFromEnvJobNode extends AsyncJobNode {

	private String db;
	private String dbParam;
	private String dbProperty;

	private String sqlParamName;

	@Resource
	private UniqueServiceLocator serviceLocator;

	@Override
	protected String execute(final NodeToken token) throws Exception {
		String sql = token.getEnv().getAttribute(sqlParamName);
		if (StringUtils.isBlank(sql)) throw new IllegalArgumentException("Missing value in env attribute named: " + sqlParamName);
		serviceLocator.getService(DatabaseService.class).updateSQL(findDb(token), sql);

		return Arc.DEFAULT_ARC;
	}

	private String findDb(final NodeToken token) {
		if (dbParam != null && !dbParam.isEmpty()) {
			return token.getEnv().getAttribute(dbParam);
		} else if (dbProperty != null && !dbProperty.isEmpty()) {
			return getPropertyFetcher().getProperty(dbProperty);
		} else {
			return db;
		}
	}

	public String getDb() {
		return db;
	}

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

	public String getDbParam() {
		return dbParam;
	}

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

	public String getDbProperty() {
		return dbProperty;
	}

	public void setDbProperty(final String dbProperty) {
		this.dbProperty = dbProperty;
	}

	public String getSqlParamName() {
		return sqlParamName;
	}

	public void setSqlParamName(final String sqlParamName) {
		this.sqlParamName = sqlParamName;
	}
}
