package rs.ac.bg.fon.ai.books.services;

import java.util.ArrayList;
import java.util.Collection;

import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.Resource;

import rs.ac.bg.fon.ai.books.persistance.RDFModel;
import rs.ac.bg.fon.ai.books.services.query.QueryExecutor;
import rs.ac.bg.fon.ai.books.util.Constants;
import rs.ac.bg.fon.ai.books.util.Schema;

public class BookService {
	
	private QueryExecutor queryExecutor = new QueryExecutor();

	public Resource createBook(String iri, String name, String award, Resource writer) {
		return RDFModel.getInstance().getModel()
				.createResource(iri, Schema.getClass("Book"))
				.addProperty(Schema.getProperty("name"), name)
				.addProperty(Schema.getProperty("award"), award)
				.addProperty(Schema.getProperty("author"), writer);
	}
	
	public Collection<String> getAllPulitzerWinners() {
		String query = 
			"PREFIX rdf: <"+Constants.RDF+"> " + 
			"PREFIX schema: <"+Constants.SCHEMA+"> " + 
			"SELECT ?writerName " +
			"WHERE { " +
				"?book rdf:type schema:Book . " +
				"?book schema:author ?writer . " +
				"?book schema:award \"Pulitzer Prize\" ." +
						
				"?writer schema:name ?writerName ." +
			"}";
	
		Collection<String> result = queryExecutor
				.executeOneVariableSelectSparqlQuery(query, "writerName",
						RDFModel.getInstance().getModel());
		
		if (result != null && !result.isEmpty()) {
			return result;
		}
		
		return new ArrayList<String>();
	}

	public Model describeBooksAboutShakespeare() {
		String query = 
			"PREFIX rdf: <"+Constants.RDF+"> " + 
			"PREFIX schema: <"+Constants.SCHEMA+"> " +
			"DESCRIBE ?book " +
			"WHERE { " +
				"?book rdf:type schema:Book . " +
				"?book schema:name ?bookName ." +

				"FILTER regex(?bookName, \"Shakespeare\", \"i\")" +
			"}";
		
		return queryExecutor
				.executeDescribeSparqlQuery(query,
						RDFModel.getInstance().getModel());
	}
}
