// 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 ?graph ?identifier ?label ?title ?uriType ?type ?uriOwner ?current_owner ?current_location ?subject (group_concat(distinct ?value ; separator='x') as ?dimensions) SAMPLE(?unit) AS ?unit (GROUP_CONCAT(DISTINCT CONCAT(?uriMaterial, '; ', ?material) ; SEPARATOR = '<br />') AS ?Materials) ?condition ?note \
WHERE { \
VALUES ?uri {<" + thisUrlParams.link + ">} \
GRAPH ?graph {?uri rdfs:label ?label} \
OPTIONAL {?uri crm:P3_has_note ?note } \
?uri crm:P128_carries ?Inf_Obj . \
OPTIONAL {?Inf_Obj crm:P1_is_identified_by ?uriTitle . \
?uriTitle rdf:type crm:E35_Title; \
rdfs:label ?title } \
OPTIONAL {?Inf_Obj crm:P2_has_type ?uriType . \
?uriType rdfs:label ?type } \
OPTIONAL {?uri crm:P43_has_dimension ?uriDimension . \
?uriDimension crm:P90_has_value ?value; \
crm:P91_has_unit ?uri_unit . \
?uri_unit rdfs:label ?unit } \
OPTIONAL {?uri crm:P1_is_identified_by ?uriIdentifier . \
?uriIdentifier rdfs:label ?identifier } \
OPTIONAL {?uri crm:P45_consists_of ?uriMaterial . \
?uriMaterial rdfs:label ?material } \
OPTIONAL {?uri crm:P44_has_condition ?uriCondition . \
?uriCondition crm:P2_has_type ?condition} \
OPTIONAL {?uri crm:P54_has_current_permanent_location ?current_location } \
OPTIONAL {?uri crm:P62_depicts ?uriSubject . \
?uriSubject rdfs:label ?subject; \
crm:P2_has_type 'Identificazione Iconografica' .} \
OPTIONAL {?uri crm:P52_has_current_owner ?uriOwner . \
?uriOwner rdfs:label ?current_owner } \
}"

queryProduction = prefixes + " SELECT DISTINCT (GROUP_CONCAT(DISTINCT CONCAT(?uriPerson, '; ', ?person, '; ', ?role) ; SEPARATOR = '<br />') AS ?Partecipants) (group_concat(distinct ?time_span ;separator='-') as ?time) (GROUP_CONCAT(DISTINCT CONCAT(?uriTecne, '; ', ?technique) ; SEPARATOR = '<br />') AS ?techniques) \
WHERE { \
VALUES ?uri {<" + thisUrlParams.link + ">} \
?uri crm:P128_carries ?Information_Object . \
?Information_Object crm:P108i_was_produced_by ?Production . \
OPTIONAL {?Production crm:P4_has_time-span ?uriTS ; \
crm:P32_used_general_technique ?uriTecne . \
?uriTS rdfs:label ?time_span . \
?uriTecne rdfs:label ?technique} \
OPTIONAL {?pc crm:P01_has_domain ?Production ; \
crm:P02_has_range ?uriPerson ; \
crm:P14.1_in_the_role_of ?uriRole . \
?uriPerson rdfs:label ?person . \
?uriRole rdfs:label ?role} \
}"


queryURL = prepareQueryURL(queryInfo);

queryPro = prepareQueryURL(queryProduction);


response = $.ajax({

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

response_Pro = $.ajax({

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


function handle_OAdata(json) {

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

  $.each(
      json['results']['bindings'],
      function (index, value) {
        var graph = value['graph']['value'];
        var label = value['label']['value'];
        var title = "";
        var type = "";
        var current_owner = "";
        var current_location = "";
        var subject = "";
        var dimensions = "";
        var materials = "";
        var condition = "";
        var note = "";
        var identifier = "";
        var unit = "";

        var dataset = get_dataset_name(graph);
        

        if (value.hasOwnProperty('title')) {
          $("#SGTT").css("display", "flex");
          title = value['title']['value'];
        }
        if (value.hasOwnProperty('identifier')) {
          $("#NCT").css("display", "flex");
          identifier = value['identifier']['value'];
        }
        if (value.hasOwnProperty('type')) {
          $("#OGTD").css("display", "flex");
          type = "<div class='d-flex'><div class='mr-3'>" +
                  value['type']['value'] + "</div><div class='d-flex ml-auto'><div class='mr-3'><a class='btn-icon' target='_blank' href='" +
                  value['uriType']['value'] + "'><i class='fa fa-bullseye' aria-hidden='true'></i><p class='btn-text'>AAT</p></a></div></div></div></div>";
        }
        if (value.hasOwnProperty('current_owner')) {
          $("#LDCN").css("display", "flex");
          current_owner = "<div class='d-flex'><div class='mr-3'>" +
                            value['current_owner']['value'] + "</div><div class='d-flex ml-auto'><div class='mr-3'><a class='btn-icon' target='_blank' href='" +
                            value['uriOwner']['value'] + "'><i class='fas fa-external-link-alt' aria-hidden='true'></i><p class='btn-text'>LINK</p></a></div></div></div></div>";
        }
        if (value.hasOwnProperty('current_location')) {
          $("#LDCS").css("display", "flex");
          current_location = value['current_location']['value'];
        }
        if (value.hasOwnProperty('unit')) {
          unit = value['unit']['value'];
        }
        if (value.hasOwnProperty('subject')) {
          $("#SGTI").css("display", "flex");
          subject = value['subject']['value'];
        }
        if (value.hasOwnProperty('dimensions')) {
          if (value['dimensions']['value'] != "") {
            $("#MIS").css("display", "flex");
            dimensions = value['dimensions']['value'];
          }
        }
        if (value.hasOwnProperty('condition')) {
          $("#STCC").css("display", "flex");
          condition = value['condition']['value'];
        }
        if (value.hasOwnProperty('note')) {
          $("#NSC").css("display", "flex");
          note = value['note']['value'];
        }
        if (value.hasOwnProperty('Materials')) {
          if (value['Materials']['value'] != "") {
            $("#MTC").css("display", "flex");
            mm = value['Materials']['value'];
            mat = mm.split("<br />");
            for (i in mat) {
                slice = mat[i].split("; ");
                /*materials += "<a href='" + slice[0] + "'>" + slice[1] + "</a><br />";*/

                materials += "<div class='d-flex'><div class='mr-3'>" +
                          slice[1] + "</div><div class='d-flex ml-auto'><div class='mr-3'><a class='btn-icon' target='_blank' href='" +
                          slice[0] + "'><i class='fa fa-bullseye' aria-hidden='true'></i><p class='btn-text'>AAT</p></a></div></div></div></div>";
            }
          }
        }

        document.getElementById("grafo").innerHTML = dataset;
        document.getElementById("nome_oggetto").innerHTML = label;
        /*document.getElementById("title").innerHTML = title;*/
        document.getElementById("identifier").innerHTML = identifier;
        document.getElementById("type").innerHTML = type;
        document.getElementById("owner").innerHTML = current_owner;
        /*document.getElementById("location").innerHTML = current_location;*/
        document.getElementById("subject").innerHTML = subject;
        document.getElementById("dimensions").innerHTML = dimensions + unit;
        document.getElementById("materials").innerHTML = materials;
        document.getElementById("condition").innerHTML = condition;
        document.getElementById("description").innerHTML = note;

        
      });
  
}

function get_dataset_name(graph) {
  var string = "Scheda Opera d'Arte";
  if (graph == "http://dev.restore.ovi.cnr.it:8890/mpp/martini") {
    string = string + " / Collezione Martini";
  }
  else if (graph == "http://dev.restore.ovi.cnr.it:8890/mpp/ospedale") {
    string = string + " / Collezione Ospedale";
  }
  else if (graph == "http://dev.restore.ovi.cnr.it:8890/mpp/datini") {
    string = string + " / Collezione Datini";
  }
  else {
    string = string;
  }
  return (string);
}


function handle_Production(json) {

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

  $.each(
      json['results']['bindings'],
      function (index, value) {
        var partecipants = "";
        var teche = "";
        var time = "";
        var client = "";
        var artist = "";
        var artist_name = "";
        

        if (value.hasOwnProperty('techniques')) {
          if (value['techniques']['value'] != "") {
            $("#MTC").css("display", "flex");
            tt = value['techniques']['value'];
            tec = tt.split("<br />");
            for (i in tec) {
                slice = tec[i].split("; ");
                /*teche += "<a href='" + slice[0] + "'>" + slice[1] + "</a><br />";*/

                teche += "<div class='d-flex'><div class='mr-3'>" +
                          slice[1] + "</div><div class='d-flex ml-auto'><div class='mr-3'><a class='btn-icon' target='_blank' href='" +
                          slice[0] + "'><i class='fa fa-bullseye' aria-hidden='true'></i><p class='btn-text'>AAT</p></a></div></div></div></div>";
            }
          }
        }
        if (value.hasOwnProperty('Partecipants')) {
          pp = value['Partecipants']['value'];
          people = pp.split("<br />");
          for (i in people) {
              slice = people[i].split("; ");
              if (slice[2] == "Committente") {
                $("#CMM").css("display", "flex");
                client += slice[1];
              } else {
                $("#AUT").css("display", "flex");
                artist_name += slice[1];
                artist += "<div class='d-flex'><div class='mr-3'>" +
                          slice[1] + "</div><div class='d-flex ml-auto'><div class='mr-3'><a class='btn-icon' target='_blank' href='" +
                          slice[0] + "'><i class='fas fa-external-link-alt' aria-hidden='true'></i><p class='btn-text'>LINK</p></a></div><div class='persona btn-icon' style='cursor:pointer' id='" +
                          slice[0] + "'><i class='fa fa-user'></i><p class='btn-text'>SCHEDA<br />PERSONA</p></div></div></div></div>";
              }
          }
        }
        
        if (value.hasOwnProperty('time')) {
          time = value['time']['value'];
        }
        
        
        document.getElementById("technique").innerHTML = teche;
        document.getElementById("time").innerHTML = time;
        /*document.getElementById("artist_name").innerHTML = artist_name;*/
        document.getElementById("artist").innerHTML = artist;
        document.getElementById("client").innerHTML = client;
        
      });
  
}


$(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);
    

  });
