/**
 * 
 */
$(document).ready(function() {


	const sparqlGenerator = sparqljs.Generator;
	const myEngine = new Comunica.QueryEngine();
	const sparqlEndpoint = "https://hdnlab1.isti.cnr.it/fuseki/commediaontosintgra/query";
	var primaCanticaLoaded = false;
	var secondaCanticaLoaded = false;
	var terzaCanticaLoaded = false;
	var listaVersi = new Set()

	//caricamento prima cantica
	$('#cantica1').on('click', function() {
		$('.canto').each(function() {
			$(this).attr("style", 'display:none');
		});
		hideListaCanti()
		$( ".minimap_container" ).remove();
		//activateMenuItem('#cantica1')
		if (!(primaCanticaLoaded)) {
			
			jsonQuery = versiCantica("Inferno");
			execQuery = new sparqlGenerator().stringify(jsonQuery);
			executeQueryVersi(execQuery);
			primaCanticaLoaded = true;
		}
		else {
			//$("#InfernoCanto_1").attr('style', 'display:block')
			$("#CantiInferno").attr('style', 'display:block')

		}
		
		

	});

	//caricamento seconda cantica
	$('#cantica2').on('click', function() {
		$('.canto').each(function() {
			$(this).attr("style", 'display:none');
		});
		hideListaCanti()
		$( ".minimap_container" ).remove();
		//activateMenuItem('#cantica2')
		if (!(secondaCanticaLoaded)) {
			
			jsonQuery = versiCantica("Purgatorio");
			execQuery = new sparqlGenerator().stringify(jsonQuery);
			executeQueryVersi(execQuery);
			secondaCanticaLoaded = true;
		}
		else {
			//$("#PurgatorioCanto_1").attr('style', 'display:block')
			$("#CantiPurgatorio").attr('style', 'display:block')

		}

	});

	//caricamento terza cantica
	$('#cantica3').on('click', function() {
		$('.canto').each(function() {
			$(this).attr("style", 'display:none');
		});
		hideListaCanti()
		$( ".minimap_container" ).remove();
		//activateMenuItem('#cantica3')
		if (!(terzaCanticaLoaded)) {
			
			jsonQuery = versiCantica("Paradiso");
			execQuery = new sparqlGenerator().stringify(jsonQuery);
			executeQueryVersi(execQuery);
			terzaCanticaLoaded = true;
		}
		else {
			//$("#ParadisoCanto_1").attr('style', 'display:block')
			$("#CantiParadiso").attr('style', 'display:block')

		}

	});

	jQuery(document).delegate('.navig-canto', 'click', function(e) {
		$('.canto').each(function() {
			$(this).attr("style", 'display:none');
		});
		$("#" + $(this).attr('name').replace(" ", "_")).attr('style', 'display:block')
		showMinimap($(this).attr('name').replace(" ", "_"))


	});

	//Utility functions

	//activate navigation menu items

	function activateMenuItem(menuItem) {
		$('.blog-nav-item').each(function() {
			$(this).attr("class", $(this).attr("class").replace(' active', ''));
		});
		$(menuItem).attr("class", $(menuItem).attr("class") + ' active');
	}

	//hides liste canti

	function hideListaCanti() {
		$("#CantiInferno").attr('style', 'display:none')
		$("#CantiPurgatorio").attr('style', 'display:none')
		$("#CantiParadiso").attr('style', 'display:none')
	}

	// utils
	function managePunctuation(stringa) {
		var tempstringa=stringa.replaceAll(" ,", ",")
		tempstringa=tempstringa.replaceAll(" .", ".")
		tempstringa=tempstringa.replaceAll(" :", ":")
		tempstringa=tempstringa.replaceAll(" !", "!")
		tempstringa=tempstringa.replaceAll(" ?", "?")
		tempstringa=tempstringa.replaceAll(" ;", ";")
		return tempstringa
	}


	//minimap management
	let minimap = document.createElement('div');
	let minimapSize = document.createElement('div');
	let viewer = document.createElement('div');
	let minimapContent = document.createElement('iframe');
	let scale=0.1;
	let realScale;
	
	function showMinimap(element) {

		
		
		

		minimap.className = 'minimap_container'
		minimapSize.className = 'minimap_size'
		viewer.className = 'minimap_viewer'
		viewer.id='minimapviewer'
		minimapContent.className = 'minimap_content'

		minimap.append(minimapSize, viewer, minimapContent);

		document.body.appendChild(minimap)
		
		let html = document.getElementById(element).innerHTML
		//console.log(html)

		let iFrameDoc = minimapContent.contentWindow.document;
		iFrameDoc.open();
		iFrameDoc.write(html);
		iFrameDoc.close();

		getDimensions()
		window.addEventListener('scroll', trackScroll)
		window.addEventListener('resize', getDimensions)
		
	}
	
	
	
	function getDimensions(){
		
		let bodyWidth = document.body.clientWidth;
	    let bodyRatio = document.body.clientHeight / bodyWidth;
	    let winRatio = window.innerHeight / window.innerWidth;
	
	    minimap.style.width = '10%';
	
	    realScale = minimap.clientWidth / (bodyWidth);
	
	    minimapSize.style.paddingTop = `${bodyRatio * 100}%`
	    viewer.style.paddingTop = `${winRatio * 100}%`;
	
	    minimapContent.style.transform = `scale(${realScale})`;
	    minimapContent.style.width = `${(100 / realScale)}%`
	    minimapContent.style.height = `${(100 / realScale)}%`
	 }

	function trackScroll(){
		viewer.style.transform=`translateY(${window.scrollY * realScale}px)`
	}

	//end minimap management

	async function executeQueryVersi(query) {
		bindingsStream = await myEngine.queryBindings(query, { sources: [{ type: 'sparql', value: sparqlEndpoint },], });
		alert(query)
		try {
			var listaCanti = new Set()
			listaVersi = new Set()
			let cantica = 0;
			bindingsStream.on('data', (binding) => {
				//cantica
				cantica = binding.get('Cantica').value;
				//la lista dei canti
				listaCanti.add(binding.get('Canto').value)
				//la lista dei versi
				var obj = new Object();
				obj.numverso = binding.get('NumeroVerso').value;
				obj.verso = binding.get('Verso').value;
				obj.canto = binding.get('Canto').value;
				obj.from = binding.get('from').value;
				obj.to = binding.get('to').value;
				listaVersi.add(obj)

			});
			bindingsStream.on('end', () => {

				var orderedListaCanti = Array.from(listaCanti)
				orderedListaCanti = orderedListaCanti.sort((a, b) => {
					if (parseInt(a.split(" ")[1]) < parseInt(b.split(" ")[1])) {
						return -1;
					}
				});

				var orderedListaVersi = Array.from(listaVersi)
				orderedListaVersi = orderedListaVersi.sort((a, b) => {
					if (parseInt(a.numverso) < parseInt(b.numverso)) {
						return -1;
					}
				});

				var divListaCanti = $('<DIV id="Canti' + cantica + '" />')
				for (canto of orderedListaCanti) {
					var licanto = $('<li class="navig-canto"/>')
					/*
					licanto.attr('name', cantica + canto)
					licanto.attr('href', "#")
					licanto.attr("style", "line-height: 1.2em")
					licanto.append(canto)

					
					licanto.appendTo(divListaCanti)
					*/
					var divcanto = $('<div />')
					var titolocanto = $('<div class="measure f3 lh-copy text-primary font-weight-lighter titolo-canto" />')
					//<div class="measure f6 lh-copy text-secondary font-weight-lighter labelCanto">
					titolocanto.append(canto)
					divcanto.attr('class', 'canto f6 font-weight-lighter')
					divcanto.attr('style', 'display:none')
					divcanto.attr('id', (cantica + canto).replace(" ", "_"))
					titolocanto.appendTo(divcanto)
					divcanto.appendTo(' .areacanti')
				}
				//divListaCanti.appendTo('#listacanti')

				for (verso of orderedListaVersi) {
					
					
					var elementoverso = $('<p />')
					elementoverso.append(verso.numverso + ". " + managePunctuation(verso.verso))
					elementoverso.attr("style", "line-height: 0.5em")
					elementoverso.attr('class', 'f6 font-weight-lighter')
					elementoverso.appendTo('#' + cantica + verso.canto.replace(" ", "_"))
					
				}


			});
		}
		catch (err) {
			console.log(err.message);
			$("#loader").hide();
		};
	};


});
