//query
ontoSparqlQuery=`PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX ecrm: <http://erlangen-crm.org/current/>
PREFIX hdn: <http://dantenetwork.it/data/commedia/>
PREFIX lemon: <http://lemon-model.net/lemon#>
PREFIX orl: <http://dantenetwork.it/ontology/ORL/>
PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
PREFIX ontolex: <http://www.w3.org/ns/lemon/ontolex#>
PREFIX olires:<https://dantenetwork.it/ontology/OLIRes/>


SELECT (?form as ?IRIForma) (?Rappresentazione as ?Forma) (?lm as ?Lemma) (?textver as ?Verso) ?NumVerso 
(?t_canto as ?Canto) (?t_cantica as ?Cantica) 


WHERE {
     ?fa orl:occurrenceOf ?form;
         ecrm:P148i_is_component_of ?ver .
     ?ver ecrm:P190_Has_Symbolic_Content ?textver;
          olires:hasNumber ?NumVerso;
          ecrm:P148i_is_component_of ?canto .
     ?canto ecrm:P102_has_title ?t_canto;
            ecrm:P148i_is_component_of ?cantica .
     ?cantica ecrm:P102_has_title ?t_cantica .
     ?form ontolex:writtenRep ?Rappresentazione .
     ?lent ontolex:lexicalForm ?form;
          ontolex:canonicalForm ?cf .
    ?cf ontolex:writtenRep ?lm .
    FILTER regex(?Rappresentazione,"^farò$","i") .
    #FILTER regex(?lm,"^fare$","i") .
    FILTER langMatches(lang(?Rappresentazione),"it")
 } ORDER BY ?Cantica ?Canto ?NumVerso 
 LIMIT 50`
//Togliere LIMIT in prod

orlprefix='http://dantenetwork.it/ontology/ORL/'

function writesparqlquery(query) {
	return (query);
}
// write the query in natural language
	
function writesearchValue(form) {
	var strq='il lemma';
	var strcategoria='in tutte le categorie'
		
	if (form.oggetto.value=='forma')
		strq='la forma';
	if (form.categoria.value!='all')
		strcategoria='nella categoria '+ form.categoria.value;
			
	return `Cerco: ${strq} ${form.query.value}, ${form.tipo.value},  ${strcategoria}`
}

// the basic initial query is parsed

function gimmespq(){
	  var SparqlParser = sparqljs.Parser;
	  var parser = new SparqlParser();
	  return parser.parse(ontoSparqlQuery);
	  
  
	}

// the query is transformed according the form values

function gimmespqfromjson(form){
	  const sparqlgen = sparqljs.Generator;
	  const generator = new sparqlgen({orl: "http://www.w3.org/2000/01/rdf-schema#" })
	  const parsedquery=gimmespq()
	  if (form.categoria.value!='all') 
	    parsedquery.where[0].triples.push(JSON.parse(data21)[form.categoria.value]);
	  if (form.query.value!="")
	    switch(form.tipo.value) {
	      case 'parola':
	        parsedquery.where[1].expression.args[1].value="^"+form.query.value+"$";
	        break;
	      case 'sottostringa':
	        parsedquery.where[1].expression.args[1].value=form.query.value;
	      break;
	      case 'prefisso':
	        parsedquery.where[1].expression.args[1].value=form.query.value;
	      break;
	      case 'suffisso':
	        parsedquery.where[1].expression.args[1].value=form.query.value+"$";
	      break;
	      default:
	        parsedquery.where[1].expression.args[1].value="^"+form.query.value+"$";
	    };
	  return generator.stringify(parsedquery);
	
}

function getStatements(){
	
	return data21
	
}

function buildSQ(stquery) {
	//alert (stquery['EsprLogica'])
	var SparqlParser = sparqljs.Parser;
	var parser = new SparqlParser();
	const parsedquery =parser.parse(ontoSparqlQuery);
	const lf = document.getElementById("lemma_forma");
	var ftxt = document.getElementById("queryText");
	//Nick
	if (ftxt==null){
		ftxt = document.getElementById("searchValue");
	}
	
	
	if (stquery['EsprLogica']!=null && stquery['EsprLogica']!='' && stquery['EsprLogica'].length==1){
		clause=stquery['EsprLogica']
		
		myquery=buildClause(stquery[clause], parsedquery)

		return (myquery)
	}
	
	if (ftxt.value.trim() != "") {
		
		if (ftxt.value.trim().slice(-1) !=='*')
			strval="^" +ftxt.value.trim()+ "$";
		else
			strval=ftxt.value.trim().slice(0, -1)
			
		parsedquery.where[1].expression.args[1].value = strval;
		if (lf.value == 'lemma')
			parsedquery.where[1].expression.args[0].value = "lm";
	}
	else{
		parsedquery.where.splice(1, 1)
	}
	
	
	return (parsedquery)

}

function buildClause(clause, parsedquery){
	
	if (clause['queryText'].trim() != "") {
		if (clause['queryText'].trim().slice(-1) !=='*')
			strval="^" +clause['queryText'].trim()+ "$";
		else
			strval=clause['queryText'].trim().slice(0, -1)
			
		parsedquery.where[1].expression.args[1].value = strval;
		if (clause['lemma_forma'] == 'lemma')
			parsedquery.where[1].expression.args[0].value = "lm";	
	}
	else{
		parsedquery.where.splice(1, 1)
	}
	if (clause['typeGramm0'] !=null && clause['typeGramm0'] != "all")
		parsedquery.where[0].triples.push(JSON.parse(data21)[clause['typeGramm0']]);
	
	
	if (clause['typeGramm0'] !=null && Object.keys(sottoCategorie).includes(clause['typeGramm0'].trim())){ 
		//sctmp=JSON.parse(sottoCategorieSostantivi)
		sctmp=sottoCategorie[clause['typeGramm0'].trim()]
		sctk=Object.keys(sctmp)
		for (ke in sctk){
			//alert (clause[sctk[ke]])
			keval=clause[sctk[ke]]
			if (keval!=null && keval!=''){
				sttmts=sctmp[sctk[ke]]
				subcatstat= buildsubcategoryClause(sttmts[keval])
				parsedquery.where[0].triples.push(subcatstat);
			}
		}
	}
		
	return parsedquery	
	
}

function buildsubcategoryClause(sttmnt){
	
	subcattmplate=`{"subject": {"termType": "Variable", "value":"form"}, 
	"predicate": {"termType":"NamedNode"}, 
	"object": {"termType": "NamedNode"}}
	`
	
	//orlprefix='http://dantenetwork.it/ontology/ORL/'
	
	
	
	predicate=orlprefix+(sttmnt.split(':')[0])
	obj=orlprefix+(sttmnt.split(':')[1])
	subcatstatement=JSON.parse(subcattmplate)
	
	subcatstatement['predicate']['value']=predicate
	subcatstatement['object']['value']=obj
	
	return (subcatstatement)
	
}


var sottoCategorie = {
		"verbovolgare": {"Diatesi": {"Attivo": "TipoDiatesiVerboVolgare:VerboVolgareAttivo", "Passivo": "TipoDiatesiVerboVolgare:VerboVolgarePassivo"},
					"Transitivita":  {"Intransitivo": "TipoTransitivitàVerboVolgare:VerboVolgareIntransitivo", "Transitivo": "TipoTransitivitàVerboVolgare:VerboVolgareTransitivo"},
					"Genere": {"Femminile": "TipoGenereVerboVolgare:GenereFemminileVerboVolgare", "Maschile": "TipoGenereVerboVolgare:GenereMaschileVerboVolgare"},
					"Numero": {"Singolare": "TipoNumeroVerboVolgare:NumeroSingolareVerboVolgare", "Plurale": "TipoNumeroVerboVolgare:NumeroPluraleVerboVolgare"},
					"Pers": {"Impersonale": "VerboVolgareImpersonale:VerboVolgareImpersonale"},
					"Rifl":{"Riflessivo": "VerboVolgareRiflessivo:VerboVolgareRiflessivo"},
					"Coniugazione": {"Prima coniugazione": "TipoConiugazioneVerboVolgare:VerboVolgarePrimaConiugazione", "Seconda coniugazione": "TipoConiugazioneVerboVolgare:VerboVolgareSecondaConiugazione",
									 "Terza coniugazione": "TipoConiugazioneVerboVolgare:VerboVolgareTerzaConiugazione", 
									 "Essere coniugazione": "TipoConiugazioneVerboVolgare:VerboVolgareAusiliareEssere",
									 "Avere coniugazione": "TipoConiugazioneVerboVolgare:VerboVolgareAusiliareAvere"},
					"Tempi": {"Indicativo presente": "TipoTempoVerboVolgare:PresenteIndicativoVerboVolgare", "Indicativo passato prossimo": "TipoTempoVerboVolgare:PassatoProssimoIndicativoVerboVolgare",
							 "Indicativo imperfetto": "TipoTempoVerboVolgare:ImperfettoIndicativoVerboVolgare", "Indicativo passato remoto": "TipoTempoVerboVolgare:PassatoRemotoIndicativoVerboVolgare",
							 "Indicativo trapassato prossimo": "TipoTempoVerboVolgare:TrapassatoProssimoIndicativoVerboVolgare", "Indicativo trapassato remoto": "TipoTempoVerboVolgare:TrapassatoRemotoIndicativoVerboVolgare",
							 "Indicativo futuro semplice": "TipoTempoVerboVolgare:FuturoSempliceIndicativoVerboVolgare", "Indicativo futuro anteriore": "TipoTempoVerboVolgare:FuturoAnterioreIndicativoVerboVolgare",
							 "Congiuntivo presente": "TipoTempoVerboVolgare:PresenteCongiuntivoVerboVolgare", "Congiuntivo imperfetto": "TipoTempoVerboVolgare:ImperfettoCongiuntivoVerboVolgare",
							 "Congiuntivo passato": "TipoTempoVerboVolgare:PassatoCongiuntivoVerboVolgare", "Congiuntivo trapassato": "TipoTempoVerboVolgare:TrapassatoCongiuntivoVerboVolgare",
							 "Condizionale presente": "TipoTempoVerboVolgare:PresenteCondizionaleVerboVolgare", "Condizionale passato": "TipoTempoVerboVolgare:PassatoCondizionaleVerboVolgare",
							 "Imperativo presente": "TipoTempoVerboVolgare:PresenteImperativoVerboVolgare", "Infinito presente": "TipoTempoVerboVolgare:PresenteInfinitoVerboVolgare",
							 "Infinito passato": "TipoTempoVerboVolgare:PassatoInfinitoVerboVolgare", "Participio presente": "TipoTempoVerboVolgare:PresenteParticipioVerboVolgare",
							 "Participio passato": "TipoTempoVerboVolgare:PassatoParticipioVerboVolgare", "Gerundio presente": "TipoTempoVerboVolgare:PresenteGerundioVerboVolgare",
							 "Gerundio passato": "TipoTempoVerboVolgare:PassatoGerundioVerboVolgare"}
					
					},
					
		"sostantivovolgare": {
					"Genere lemma": {"Lemma femminile": "TipoGenereLemmaSostantivoVolgare:GenereFemminileLemmaSostantivoVolgare", "Lemma maschile": "TipoGenereLemmaSostantivoVolgare:GenereMaschileLemmaSostantivoVolgare"},
					"Genere forma": {"Forma femminile": "TipoGenereSostantivoVolgare:GenereFemminileSostantivoVolgare", "Forma maschile": "TipoGenereSostantivoVolgare:GenereMaschileSostantivoVolgare"},
					"Numero": {"Singolare": "TipoNumeroSostantivoVolgare:NumeroSingolareSostantivoVolgare", "Plurale": "TipoNumeroSostantivoVolgare:NumeroPluraleSostantivoVolgare"},
					"riflpers": {"In locuzione": "SostantivoVolgareInLocuzione:Lv_lv"},
					"Declinazione sostantivo": {"Prima declinazione": "TipoDeclinazioneSostantivoVolgare:PrimaDeclinazioneSostantivoVolgare", "Seconda declinazione": "TipoDeclinazioneSostantivoVolgare:SecondaDeclinazioneSostantivoVolgare",
									            "Terza declinazione": "TipoDeclinazioneSostantivoVolgare:TerzaDeclinazioneSostantivoVolgare"}
					},
					
		"pronomevolgare": "filtripronome",
		"aggettivovolgare": "filtriaggettivo",
		"articolovolgare": "filtriarticolo",
		"avverbiovolgare": "filtriavverbio",
		"preposizionevolgare": "filtripreposizione",
		"congiunzionevolgare": "filtricongiunzione",
		"onomasticavolgare": {
					"Tipo" :{"Nome proprio":"TipoDellOnomasticaVolgare:NomeProprio", "Nome proprio separato":"TipoDellOnomasticaVolgare:NomeProprioSeparato",
					        "Titolo": "TipoDellOnomasticaVolgare:Titolo"}
					},
					
		"citazionevolgare": "filtricitazione"
	}


data21 = `{"verbovolgare": {"subject": {"termType": "Variable", "value":"form"}, "predicate": {"termType":"NamedNode", "value": "http://www.w3.org/1999/02/22-rdf-syntax-ns#type"}, "object": {"termType": "NamedNode", "value": "http://dantenetwork.it/ontology/ORL/FormaVerboVolgare"}},
	"sostantivovolgare": {"subject": {"termType": "Variable", "value":"form"}, "predicate": {"termType":"NamedNode", "value": "http://www.w3.org/1999/02/22-rdf-syntax-ns#type"}, "object": {"termType": "NamedNode", "value": "http://dantenetwork.it/ontology/ORL/FormaSostantivoVolgare"}},
	"aggettivovolgare": {"subject": {"termType": "Variable", "value":"form"}, "predicate": {"termType":"NamedNode", "value": "http://www.w3.org/1999/02/22-rdf-syntax-ns#type"}, "object": {"termType": "NamedNode", "value": "http://dantenetwork.it/ontology/ORL/FormaAggettivoVolgare"}},
	"avverbiovolgare": {"subject": {"termType": "Variable", "value":"form"}, "predicate": {"termType":"NamedNode", "value": "http://www.w3.org/1999/02/22-rdf-syntax-ns#type"}, "object": {"termType": "NamedNode", "value": "http://dantenetwork.it/ontology/ORL/FormaAvverbioVolgare"}},
	"pronomevolgare": {"subject": {"termType": "Variable", "value":"form"}, "predicate": {"termType":"NamedNode", "value": "http://www.w3.org/1999/02/22-rdf-syntax-ns#type"}, "object": {"termType": "NamedNode", "value": "http://dantenetwork.it/ontology/ORL/FormaPronomeVolgare"}},
	"congiunzionevolgare": {"subject": {"termType": "Variable", "value":"form"}, "predicate": {"termType":"NamedNode", "value": "http://www.w3.org/1999/02/22-rdf-syntax-ns#type"}, "object": {"termType": "NamedNode", "value": "http://dantenetwork.it/ontology/ORL/FormaCongiunzioneVolgare"}},
	"articolovolgare": {"subject": {"termType": "Variable", "value":"form"}, "predicate": {"termType":"NamedNode", "value": "http://www.w3.org/1999/02/22-rdf-syntax-ns#type"}, "object": {"termType": "NamedNode", "value": "http://dantenetwork.it/ontology/ORL/FormaArticoloVolgare"}},
	"preposizionevolgare": {"subject": {"termType": "Variable", "value":"form"}, "predicate": {"termType":"NamedNode", "value": "http://www.w3.org/1999/02/22-rdf-syntax-ns#type"}, "object": {"termType": "NamedNode", "value": "http://dantenetwork.it/ontology/ORL/FormaPreposizioneVolgare"}},
	"interiezionevolgare": {"subject": {"termType": "Variable", "value":"form"}, "predicate": {"termType":"NamedNode", "value": "http://www.w3.org/1999/02/22-rdf-syntax-ns#type"}, "object": {"termType": "NamedNode", "value": "http://dantenetwork.it/ontology/ORL/FormaInteriezioneVolgare"}},
	"onomasticavolgare": {"subject": {"termType": "Variable", "value":"form"}, "predicate": {"termType":"NamedNode", "value": "http://www.w3.org/1999/02/22-rdf-syntax-ns#type"}, "object": {"termType": "NamedNode", "value": "http://dantenetwork.it/ontology/ORL/FormaOnomasticaVolgare"}},
	"citazionevolgare": {"subject": {"termType": "Variable", "value":"form"}, "predicate": {"termType":"NamedNode", "value": "http://www.w3.org/1999/02/22-rdf-syntax-ns#type"}, "object": {"termType": "NamedNode", "value": "http://dantenetwork.it/ontology/ORL/FormaCitazioneVolgare"}}, 
	"locuzionevolgare": {"subject": {"termType": "Variable", "value":"form"}, "predicate": {"termType":"NamedNode", "value": "http://www.w3.org/1999/02/22-rdf-syntax-ns#type"}, "object": {"termType": "NamedNode", "value": "http://dantenetwork.it/ontology/ORL/FormaLocuzioneVolgare"}}
	}
	`
	
	
		
sottoCategorieVerbi=`{"Diatesi": {"Attivo": "TipoDiatesiVerboVolgare:VerboVolgareAttivo", "Passivo": "TipoDiatesiVerboVolgare:VerboVolgarePassivo"},
					"Transitivita":  {"Intransitivo": "TipoTransitivitàVerboVolgare:VerboVolgareIntransitivo", "Transitivo": "TipoTransitivitàVerboVolgare:VerboVolgareTransitivo"},
					"Genere": {"Femminile": "TipoGenereVerboVolgare:GenereFemminileVerboVolgare", "Maschile": "TipoGenereVerboVolgare:GenereMaschileVerboVolgare"},
					"Numero": {"Singolare": "TipoNumeroVerboVolgare:NumeroSingolareVerboVolgare", "Plurale": "TipoNumeroVerboVolgare:NumeroPluraleVerboVolgare"},
					"Pers": {"Impersonale": "VerboVolgareImpersonale:VerboVolgareImpersonale"},
					"Rifl":{"Riflessivo": "VerboVolgareRiflessivo:VerboVolgareRiflessivo"},
					"Coniugazione": {"Prima coniugazione": "TipoConiugazioneVerboVolgare:VerboVolgarePrimaConiugazione", "Seconda coniugazione": "TipoConiugazioneVerboVolgare:VerboVolgareSecondaConiugazione",
									 "Terza coniugazione": "TipoConiugazioneVerboVolgare:VerboVolgareTerzaConiugazione", 
									 "Essere coniugazione": "TipoConiugazioneVerboVolgare:VerboVolgareAusiliareEssere",
									 "Avere coniugazione": "TipoConiugazioneVerboVolgare:VerboVolgareAusiliareAvere"},
					"Tempi": {"Indicativo presente": "TipoTempoVerboVolgare:PresenteIndicativoVerboVolgare", "Indicativo passato prossimo": "TipoTempoVerboVolgare:PassatoProssimoIndicativoVerboVolgare",
							 "Indicativo imperfetto": "TipoTempoVerboVolgare:ImperfettoIndicativoVerboVolgare", "Indicativo passato remoto": "TipoTempoVerboVolgare:PassatoRemotoIndicativoVerboVolgare",
							 "Indicativo trapassato prossimo": "TipoTempoVerboVolgare:TrapassatoProssimoIndicativoVerboVolgare", "Indicativo trapassato remoto": "TipoTempoVerboVolgare:TrapassatoRemotoIndicativoVerboVolgare",
							 "Indicativo futuro semplice": "TipoTempoVerboVolgare:FuturoSempliceIndicativoVerboVolgare", "Indicativo futuro anteriore": "TipoTempoVerboVolgare:FuturoAnterioreIndicativoVerboVolgare",
							 "Congiuntivo presente": "TipoTempoVerboVolgare:PresenteCongiuntivoVerboVolgare", "Congiuntivo imperfetto": "TipoTempoVerboVolgare:ImperfettoCongiuntivoVerboVolgare",
							 "Congiuntivo passato": "TipoTempoVerboVolgare:PassatoCongiuntivoVerboVolgare", "Congiuntivo trapassato": "TipoTempoVerboVolgare:TrapassatoCongiuntivoVerboVolgare",
							 "Condizionale presente": "TipoTempoVerboVolgare:PresenteCondizionaleVerboVolgare", "Condizionale passato": "TipoTempoVerboVolgare:PassatoCondizionaleVerboVolgare",
							 "Imperativo presente": "TipoTempoVerboVolgare:PresenteImperativoVerboVolgare", "Infinito presente": "TipoTempoVerboVolgare:PresenteInfinitoVerboVolgare",
							 "Infinito passato": "TipoTempoVerboVolgare:PassatoInfinitoVerboVolgare", "Participio presente": "TipoTempoVerboVolgare:PresenteParticipioVerboVolgare",
							 "Participio passato": "TipoTempoVerboVolgare:PassatoParticipioVerboVolgare", "Gerundio presente": "TipoTempoVerboVolgare:PresenteGerundioVerboVolgare",
							 "Gerundio passato": "TipoTempoVerboVolgare:PassatoGerundioVerboVolgare"}
					
					}
					`

sottoCategorieSostantivi=`{
					"Genere lemma": {"Lemma femminile": "TipoGenereLemmaSostantivoVolgare:GenereFemminileLemmaSostantivoVolgare", "Lemma maschile": "TipoGenereLemmaSostantivoVolgare:GenereMaschileLemmaSostantivoVolgare"},
					"Genere forma": {"Forma femminile": "TipoGenereSostantivoVolgare:GenereFemminileSostantivoVolgare", "Forma maschile": "TipoGenereSostantivoVolgare:GenereMaschileSostantivoVolgare"},
					"Numero": {"Singolare": "TipoNumeroSostantivoVolgare:NumeroSingolareSostantivoVolgare", "Plurale": "TipoNumeroSostantivoVolgare:NumeroPluraleSostantivoVolgare"},
					"riflpers": {"In locuzione": "SostantivoVolgareInLocuzione:Lv_lv"},
					"Declinazione sostantivo": {"Prima declinazione": "TipoDeclinazioneSostantivoVolgare:PrimaDeclinazioneSostantivoVolgare", "Seconda declinazione": "TipoDeclinazioneSostantivoVolgare:SecondaDeclinazioneSostantivoVolgare",
									            "Terza declinazione": "TipoDeclinazioneSostantivoVolgare:TerzaDeclinazioneSostantivoVolgare"}
					}
					`

//sottoCategorie=`{"verbovolgare": ["Diatesi,2", "Transitivita,2", "Genere,2", "Numero,2", "Pers,1", "Rifl,1", "Coniugazione,n", "Tempi,n", "Persona,n", "Funzione,n", "Declinazione,n"],
//"sostantivovolgare":  ["pippo,2", "pluto,2"]}`