/**
 * 
 */
package eu.dnetlib.data.collective.transformation.engine.functions;

import java.io.StringReader;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Node;
import org.xml.sax.InputSource;

import eu.dnetlib.data.collective.transformation.IDatabaseConnector;
import eu.dnetlib.data.collective.transformation.TransformationException;

/**
 * @author jochen
 *
 */
public class Dblookup extends AbstractTransformationFunction {

	public static final String paramSqlExpr = "sqlExpr";
	private IDatabaseConnector dbConnector;
	/**
	 * 
	 */
	public Dblookup() {
		// TODO Auto-generated constructor stub
	}

	/* (non-Javadoc)
	 * @see eu.dnetlib.data.collective.transformation.engine.functions.AbstractTransformationFunction#execute()
	 */
	@Override
	String execute() throws ProcessingException {
		// TODO Auto-generated method stub
		return null;
	}

	/**
	 * @return the dbConnector
	 */
	public IDatabaseConnector getDbConnector() {
		return dbConnector;
	}

	/**
	 * @param dbConnector the dbConnector to set
	 */
	public void setDbConnector(IDatabaseConnector dbConnector) {
		this.dbConnector = dbConnector;
	}

	public LookupRecord getResults(String aSqlExpression) throws TransformationException, XPathExpressionException {
		LookupRecord lookupRecord = new LookupRecord();
		XPath xpath = XPathFactory.newInstance().newXPath();

		for (String record: dbConnector.getResult(aSqlExpression)){
			InputSource inSource = new InputSource(new StringReader(record));
			Node root = (Node)xpath.evaluate("/", inSource, XPathConstants.NODE);
			lookupRecord.setRecord(xpath.evaluate("//FIELD[@name='accessinfopackage']/text()", root), 
					"officialname",	xpath.evaluate("//FIELD[@name='officialname']/text()", root));
			lookupRecord.setRecord(xpath.evaluate("//FIELD[@name='accessinfopackage']/text()", root), 
					"id",	xpath.evaluate("//FIELD[@name='id']/text()", root));
		}
		return lookupRecord;
	}

}
