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

import java.io.IOException;

import javax.annotation.Resource;

import org.apache.commons.io.IOUtils;

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;

public class ExecuteSqlJobNode extends AsyncJobNode {

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

	private String sql;

	@Resource
	private UniqueServiceLocator serviceLocator;

	@Override
	protected String execute(final NodeToken token) throws Exception {
		serviceLocator.getService(DatabaseService.class).updateSQL(findDb(token), fetchSqlAsText(sql));

		return Arc.DEFAULT_ARC;
	}

	private String fetchSqlAsText(final String path) throws IOException {
		return IOUtils.toString(getClass().getResourceAsStream(path));
	}

	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 getSql() {
		return sql;
	}

	public void setSql(final String sql) {
		this.sql = sql;
	}

}
