// Raccatto i parametri dall'URL -- mi aspetto un parametro di nome 'link'!
thisUrlParams = {};
window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
    thisUrlParams[key] = value;
});
console.log('URL get params: ', thisUrlParams);

// Funzioni per eseguire le queries
function prepareQueryURL(query){
    sparqlEndpoint = 'http://dev.restore.ovi.cnr.it:8890/sparql/';
    sparqlUrlParams = '?default-graph-uri=&query=' + encodeURIComponent(query) + '&output=json&callback=?';
    return sparqlEndpoint + sparqlUrlParams;
}

function doJsonQuery(query){

    queryURL = prepareQueryURL(query);

    response = $.ajax({//OGGETTO

        url: queryURL,
        dataType: "json",
        success: function (data){},
        error: function (e) {}
    });

    return response;

}

// Funzioni per raccattare + stringhificare l'output
queryStringOutput = "";
function stringifyResponse(val){
    resultArray = val['results']['bindings'];
    out = "";
    for(i = 0; i < resultArray.length; i++){
        out = out + JSON.stringify(resultArray[i])
    }
    queryStringOutput = (queryStringOutput + out).replace("}{",",");
}

prefixes = "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> \
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> \
PREFIX crm: <http://www.cidoc-crm.org/cidoc-crm/> \
PREFIX owl: <http://www.w3.org/2002/07/owl#> \
PREFIX schema: <http://schema.org/> \
PREFIX foaf: <http://xmlns.com/foaf/0.1/> \
PREFIX person: <http://www.w3.org/ns/person#>"

queryInfo = prefixes + " SELECT DISTINCT ?g AS ?graph ?uri ?label ?id (group_concat(distinct ?dimension ; separator='<br />') as ?dimensions) ?material ?location ?note \
WHERE { \
VALUES ?uri {<" + thisUrlParams.link + ">} \
GRAPH ?g { ?uri rdfs:label ?label } \
OPTIONAL {?uri crm:P1_is_identified_by ?uri_id . \
?uri_id rdfs:label ?id } \
OPTIONAL { ?uri crm:P43_has_dimension ?uri_dimension . \
?uri_dimension rdfs:label ?dimension } \
OPTIONAL { ?uri crm:P45_consist_of ?uri_material . \
?uri_material rdfs:label ?material } \
OPTIONAL { ?uri crm:P54_has_current_permanent_location ?uri_location . \
?uri_location rdfs:label ?location } \
OPTIONAL { ?uri crm:P3_has_note ?uri_note . \
?uri_note rdfs:label ?note } \
} "

queryContent = prefixes + " SELECT DISTINCT ?g AS ?graph ?uri ?titolo ?tipo ?ref \
WHERE { \
VALUES ?object {<" + thisUrlParams.link + ">} \
?object crm:P128_carries ?uri . \
GRAPH ?g { ?uri rdfs:label ?label } \
OPTIONAL {?uri crm:P1_is_identified_by ?uri_titolo . \
?uri_titolo rdfs:label ?titolo . } \
OPTIONAL { ?uri crm:P2_has_type ?uri_tipo . \
?uri_tipo rdfs:label ?tipo . } \
OPTIONAL { ?uri crm:P67_refers_to ?uri_ref . \
?uri_ref rdfs:label ?ref . } \
}"


queryURL = prepareQueryURL(queryInfo);

queryINF = prepareQueryURL(queryContent);


response = $.ajax({

    url: queryURL,
    dataType: "json",
    success: function (data){
      handle_objectData(data);
    },
    error: function (e) {}
});

response_info = $.ajax({

    url: queryINF,
    dataType: "json",
    success: function (data){
    	handle_objectInfo(data);
    },
    error: function (e) {}
});


function handle_objectData(json) {

  console.log(json['results']['bindings']);

  $.each(
      json['results']['bindings'],
      function (index, value) {
        var graph = value['graph']['value'];
        var label = value['label']['value'];
        var identifier = "";
        var dimensions = "";
        var materials = "";
        var current_location = "";
        var description = "";

        
        if (value.hasOwnProperty('id')) {
          $("#ID").css("display", "flex");
          identifier = value['id']['value'];
        }
        if (value.hasOwnProperty('dimensions')) {
          if (value['dimensions']['value'] != "") {
            $("#consistenza").css("display", "flex");
            dimensions = value['dimensions']['value'];
          }
        }
        if (value.hasOwnProperty('condition')) {
          $("#STCC").css("display", "flex");
          condition = value['condition']['value'];
        }
        if (value.hasOwnProperty('material')) {
          $("#materia").css("display", "flex");
          materials = value['material']['value'];
        }
        if (value.hasOwnProperty('location')) {
          $("#localizzazione").css("display", "flex");
          current_location = value['location']['value'];
        }
        if (value.hasOwnProperty('note')) {
          $("#notes").css("display", "flex");
          description = value['note']['value'];
        }
        

        document.getElementById("grafo").innerHTML = graph;
        document.getElementById("nome_oggetto").innerHTML = label;
        document.getElementById("identifier").innerHTML = identifier;
        document.getElementById("location").innerHTML = current_location;
        document.getElementById("nota").innerHTML = description;
        document.getElementById("dimensions").innerHTML = dimensions;
        document.getElementById("materials").innerHTML = materials;
       
        
      });
  
}


function handle_objectInfo(json) {

  console.log(json['results']['bindings']);

  $.each(
      json['results']['bindings'],
      function (index, value) {

        var title = "";
        var type = "";
        var subject = "";
        

        if (value.hasOwnProperty('titolo')) {
          $("#titolo").css("display", "flex");
          title = value['titolo']['value'];
        }
        if (value.hasOwnProperty('tipo')) {
          $("#tipo").css("display", "flex");
          type = value['tipo']['value'];
        }
        if (value.hasOwnProperty('ref')) {
          $("#argomento").css("display", "flex");
          subject = value['ref']['value'];
        }
        
        
        document.getElementById("title").innerHTML = title;
        document.getElementById("type").innerHTML = type;
        document.getElementById("subject").innerHTML = subject;
        
        
      });
  
}


$(document).on("click", ".luogo", function (ev) {

    var link = this.id;
    //alert(nome_autore);
    //$('#myModal').text("");
    window.open("Luogo.html?link="+this.id);
    

  });

$(document).on("click", ".persona", function (ev) {

    var link = this.id;
    //alert(nome_autore);
    //$('#myModal').text("");
    window.open("Persona.html?link="+this.id);
    

  });
