package eu.dnetlib.ariadneplus.virtuoso;

import java.io.IOException;

import eu.dnetlib.ariadneplus.publisher.AriadnePlusPublisherException;
import eu.dnetlib.ariadneplus.publisher.SaxonHelper;
import eu.dnetlib.ariadneplus.rdf.RecordParserHelper;
import net.sf.saxon.s9api.SaxonApiException;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.springframework.core.io.ClassPathResource;
import virtuoso.jena.driver.VirtModel;

/**
 * Created by Alessia Bardi on 12/07/2017.
 *
 * @author Alessia Bardi
 */
@Ignore
@RunWith(JUnit4.class)
public class VirtuosoClientTest {

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

	private String testGraph = "virt:test";
	//private String connectionString = "jdbc:virtuoso://localhost:1111";
	private String connectionString = "jdbc:virtuoso://virtuoso.ariadneplus.d4science.org:1111";
	private String testUser = "dba";
	private String testPwd = "dba";
	private String defaultURIBaseURl = "http://test/";

	private String recordPath = "eu/dnetlib/ariadneplus/virtuoso/test_record_plain.xml";

	private VirtuosoClient client;

	private SaxonHelper saxonHelper = new SaxonHelper();


	@Before
	public void prepare() throws SaxonApiException {
		RecordParserHelper rph = new RecordParserHelper();
		rph.setSaxonHelper(saxonHelper);
		rph.init();
		client = new VirtuosoClient(connectionString, testUser, testPwd, rph, defaultURIBaseURl);
	}

	@Test
	public void testConnection(){
		VirtModel.openDatabaseModel("x", connectionString, testUser, testPwd);
	}



	@Test
	public void testFeedProvenance(){
		long res = client.feedProvenance("ariadne_____::0002b8b77eb2d6c62f61c6e1a1ce6891", "2017-05-14T12:06:38.152+02:00" , "2017-05-14T12:11:55.573", "ARIADNE", "ariadne_api");
		Assert.assertEquals(3, res);
	}

	@Test
	public void testRecord() throws AriadnePlusPublisherException {
		System.out.println(client.feed(getString(recordPath)));
	}

	@Test
	public void testRemoveFromProvenance(){
		long res = client.feedProvenance("ariadne_____::0002b8b77eb2d6c62f61c6e1a1ce6891", "2017-05-14T12:06:38.152+02:00" , "2017-05-14T12:11:55.573", "ARIADNE", "ariadne_api");
		Assert.assertEquals(3, res);
		long deleted = client.drop("ariadne_api");
		Assert.assertEquals(0, deleted);
	}

	private String getString(final String classpath) {
		try {
			final ClassPathResource resource = new ClassPathResource(classpath);
			return IOUtils.toString(resource.getInputStream(), "UTF-8");
		}catch(IOException e){
			return null;
		}
	}
}
