package ua.be.wee.model.repository;

import org.apache.jena.query.QueryExecution;
import org.apache.jena.query.ResultSet;
import org.apache.jena.rdfconnection.RDFConnectionFuseki;
import org.apache.jena.rdfconnection.RDFConnectionRemoteBuilder;
import org.apache.jena.sparql.exec.http.QueryExecutionHTTP;
import org.apache.jena.update.UpdateFactory;
import org.apache.jena.update.UpdateRequest;

public class FusekiWrapper {
	
	private static FusekiWrapper instance;
	
	private RDFConnectionRemoteBuilder builder;
	
	private String serviceURI;
	

	public String getServiceURI() {
		return serviceURI;
	}

	private FusekiWrapper() {
		
	}
	
	public static FusekiWrapper getInstance() {
		if (instance == null) {
			instance = new FusekiWrapper();
		}
		return instance;
	}

	public void setServiceURI(String serviceURI) {
		this.serviceURI = serviceURI;
		builder = RDFConnectionFuseki.create()
	            .destination(serviceURI);
	}
	
	public ResultSet execQuery(String queryStr) {
		if (!"".equals(serviceURI)) {
			QueryExecution q = QueryExecutionHTTP.service(serviceURI, queryStr);
			return q.execSelect();
		}
		throw new NullPointerException("Service URI not specified");
		
	}
	
	public boolean updateQuery(String query) {
		if (!"".equals(serviceURI)) {
			try {
				RDFConnectionFuseki conn = (RDFConnectionFuseki) builder.build();
				UpdateRequest request = UpdateFactory.create();
				request.add(query);
				conn.update(request);
				conn.close();
				return true;
			} catch (Exception e) {
				e.printStackTrace();
				return false;
			}
			
		}
		throw new NullPointerException("Service URI not specified");

	}
	
	public boolean testEndpoint() {
		String query = "PREFIX pm: <http://ua.be/sdo2l/vocabulary/formalisms/pm#>\n" 
				+ "SELECT ?pm WHERE {\n"
				+ "  ?pm a pm:Model .\n"
				+ "}";
		QueryExecutionHTTP service = QueryExecutionHTTP.service(serviceURI, query);
		ResultSet execSelect;
		try {
			execSelect = service.execSelect();
		} catch (Exception e) {
			return false;
		}
		return execSelect.hasNext();
	}
}