// Set the size of the diagram.
var width = $(document).width();
var height = $(document).height();

var duration = 750;

// Read in graph data.
var g = graphlibDot.read(design);

// Determining max label length for deciding on node separation distance.
var totalNodes = Object.keys(g._nodes).length;
var lengths = [];
for(var k = 0; k < totalNodes; k++) {
  var key = Object.keys(g._nodes)[k];
  thislabel = g._nodes[key].label;
  lengths.push(thislabel.length);
}
var maxLabelLength = Math.max(...lengths);

// Round the edges of nodes.
g.nodes().forEach(function(v) {
  var node = g.node(v);
  node.rx = node.ry = 5;
});

// Making the zoom functionality.
function zoom() {
  svgGroup.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale +")");
}

var zoomListener = d3.behavior.zoom().scaleExtent([0.1, 3]).on("zoom", zoom);

// Function to centre node when clicked so it doesn't get lost when collapsing/expanding many children.
function centreNode(source) {
  var scale = zoomListener.scale();
  var x = -source.y0;
  var y = -source.x0;
  x = x * scale + width / 2;
  y = y * scale + height / 2;
  // Update the nodes...
  d3.select('g').transition()
                .duration(duration)
                .attr("transform", "translate(" + x + "," + y + ")scale(" + scale +")");
  zoomListener.scale(scale);
  zoomListener.translate([x, y]);
}

// Create the renderer.
var render = new dagreD3.render();

// Put an svg inside the graph container.
var svg = d3.select("#graph-container").append("svg")
                                       .attr("width", width)
                                       .attr("height", height)
                                       .attr("class", "overlay")
                                       .call(zoomListener);

// Set up an SVG group so that we can translate the final graph.
var svgGroup = svg.append("g");

// Run the renderer. This is what draws the final graph.
var thingtorender = d3.select("svg g");
render(thingtorender, g);