package eu.dnetlib.ariadneplus.workflows.nodes;

import eu.dnetlib.enabling.resultset.factory.ResultSetFactory;
import eu.dnetlib.msro.workflows.graph.Arc;
import eu.dnetlib.msro.workflows.nodes.AsyncJobNode;
import eu.dnetlib.msro.workflows.procs.Env;
import eu.dnetlib.rmi.common.ResultSet;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

/**
 * Created by Alessia Bardi on 26/01/2018.
 *
 * @author Alessia Bardi
 */
public class ReadVirtuosoJobNode extends AsyncJobNode {

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

	private String datasourceName;
	private String datasourceInterface;
	private String virtuosoReaderAPIUrl;
	private int readTimeout = 30000;

	@Autowired
	private ResultSetFactory rsFactory;

	@Override
	protected String execute(final Env env){
		log.info("Using virtuoso reader at : " + getVirtuosoReaderAPIUrl());
		RestTemplate restTemplate = new RestTemplate(getClientHttpRequestFactory());

		VirtuosoAriadnePlusIterator iterator = new VirtuosoAriadnePlusIterator().datasourceInterface(getDatasourceInterface()).virtuosoReaderAPIUrl(getVirtuosoReaderAPIUrl()).datasourceName(getDatasourceName()).restTemplate(restTemplate);
		ResultSet<String> rs = rsFactory.createResultSet(() -> iterator);

		env.setAttribute("virtuoso_rs", rs);

		return Arc.DEFAULT_ARC;
	}


	protected ClientHttpRequestFactory getClientHttpRequestFactory() {
		HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory();
		clientHttpRequestFactory.setReadTimeout(readTimeout);
		return clientHttpRequestFactory;
	}

	public String getDatasourceName() {
		return datasourceName;
	}

	public void setDatasourceName(final String datasourceName) {
		this.datasourceName = datasourceName;
	}

	public String getDatasourceInterface() {
		return datasourceInterface;
	}

	public void setDatasourceInterface(final String datasourceInterface) {
		this.datasourceInterface = datasourceInterface;
	}

	public String getVirtuosoReaderAPIUrl() {
		return virtuosoReaderAPIUrl;
	}

	public void setVirtuosoReaderAPIUrl(final String virtuosoReaderAPIUrl) {
		this.virtuosoReaderAPIUrl = virtuosoReaderAPIUrl;
	}

	public int getReadTimeout() {
		return readTimeout;
	}

	public void setReadTimeout(final int readTimeout) {
		this.readTimeout = readTimeout;
	}

	public ResultSetFactory getRsFactory() {
		return rsFactory;
	}
}
