<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

	<!-- lib CSS -->
	<link rel="stylesheet" type="text/css" href="./lib/css/qlobbe.css">

	<!-- lib JS -->
	<script type="text/javascript" src="./lib/js/jquery-3.4.1.min.js"></script>
	<script type="text/javascript" src="./lib/js/bootstrap.min.js"></script>
	<script type="text/javascript" src="./lib/js/d3.min.js"></script>

	<title>Mèmiescape</title>

</head>
<body>
	<div id="main">
		<div id="viz"></div>
	</div>

	<script type="text/javascript">

		/*
		 * Draw functions
		 */		

		function draw(phyloData) {

			// set up margin 

			var margin = {t:0, r:30, b:15, l:0};
			var w = document.getElementById("viz").offsetWidth - margin.l - margin.r,
				h = $(window).height() - margin.t - margin.b;

			// draw svg view			

			var svg = d3.select("#viz").append("svg")
				.attr("width",w)
				.attr("height",h);			

			var g = svg.append("g").attr("id","svg-view");

			// draw phylomemy from an url

			d3.xml(phyloData).then(data => {
				var newNodes = document.importNode(data.documentElement,true);
				svg.attr("viewBox", newNodes.getAttribute("viewBox"));
				g.each(function(){
					this.appendChild(newNodes);
				})
				svg.call(zoom)

				d3.select("#viz")
					.append('button')
					.attr("type","button")
					.attr("id","btn_reset")
					.attr("class","btn btn-light")
					.text("reset");	

				d3.select("#btn_reset").on("click", reset);								
			})				

			// set up d3 zoom

			var transform = d3.zoomIdentity;

			zoom = d3.zoom()
				.scaleExtent([1, 50])
				.on("zoom", zoomed);

			function zoomed() {
				g.attr("transform", d3.event.transform);
			}

			function reset() {
				svg.transition().call(zoom.transform, d3.zoomIdentity);
			}

		}

		/*
		 * Control functions
		 */

		window.onload = function() {
			clean()
      var url = window.location.href;
      // console.log(url);
			readUrl(url)

		};


		/* Get a Phylo file from an URL */
		function readUrl(url) {

			var node = url.match(/nodeId=(.*)/);
			if (node != null) {
				fetch("http://localhost:8008" + "/api/v1.0/node/" + node[1] + "/phylo")
				//fetch("https://dev.gargantext.org" + "/api/v1.0/node/" + node[1] + "/phylo")
				//fetch(window.location.origin + "/api/v1.0/node/" + node[1] + "/phylo")
				  .then(res => res.blob()) 
				  .then(blob => {

					var reader = new FileReader();
					reader.onload = (function(phyloFile) {
						return function(e) {
								draw(e.target.result)
						};
					})(blob);
					reader.readAsDataURL(blob);
				});	
			} else {
				try {
				    throw new Error("Unable to find a nodeId");
				} catch (e) {
				    console.log(e.name + ": " + e.message);
				}				
			}
		}

		/* Clean the view each time you load a new phylomemy */
		function clean() {
			d3.select("svg").remove();
			d3.select("#btn_reset").remove();
		}
	
	</script>
</body>
</html>