{% load static %}

<div id="tree"></div>

<script src="{% static "prosoul/d3.min.js" %}"></script>

<script>

var margin = {top: 20, right: 120, bottom: 20, left: 10},
    width = 1100 - margin.right - margin.left,
    height = 1024 - margin.top - margin.bottom;

var i = 0,
    duration = 750,
    root;

var tree = d3.layout.tree()
    .size([height, width]);

var diagonal = d3.svg.diagonal()
    .projection(function(d) { return [d.y, d.x]; });

var svg = d3.select("div#tree").append("svg")
    .attr("width", width + margin.right + margin.left)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

var myattrs = {};
var mymetrics = {};

var myattrs = JSON.parse('{{attributes_data_str|safe}}')['children'];
var mymetrics = JSON.parse('{{metrics_data_str|safe}}')['children'];
// Only one quality model supported yet. Get the first one.
var qm = JSON.parse('{{qm_data_str|safe}}');

show_tree();

function show_tree() {
  root = qm;
  root.x0 = height / 2;
  root.y0 = 0;

  function collapse(d) {
    if (d.children) {
      d._children = d.children;
      d._children.forEach(collapse);
      d.children = null;
    }
  }

  function firstCollapse(d) {
    if (d.children) {
      d._children = d.children;
      for(i=0;i<d._children.length;i++) {
        d._children[i].children.forEach(collapse);
      }
    }
  }

  //root.children.forEach(firstCollapse);
  update(root);
}


function update(source) {

  var tabs = [0, 100, 200, 400, 630, 700];

  // Compute the new tree layout.
  var nodes = tree.nodes(root).reverse(),
      links = tree.links(nodes);

  // Normalize for fixed-depth.
  nodes.forEach(function(d, i) {
    d.y = tabs[d.depth];
  });

  // Update the nodes…
  var node = svg.selectAll("g.node")
      .data(nodes, function(d) { return d.id || (d.id = ++i); });

  // Enter any new nodes at the parent's previous position.
  var nodeEnter = node.enter().append("g")
      .attr("class", "node")
      .attr("transform", function(d) { return "translate(" + source.y0 + "," + source.x0 + ")"; })
      .on("click", click);

  nodeEnter.append("circle")
      .attr("r", 1e-6)
      .style("fill", function(d) { return d._children ? "lightsteelblue" : "#fff"; });

  nodeEnter.append("text")
      .attr("x", function(d) { return d.children || d._children ? -20 : 20; })
      .attr("dy", function(d) { return d.children || d._children ? "-0.5em" : ".35em" })
      .attr("text-anchor", function(d) { return d.children || d.children ? "end" : "start"; })
      .attr("fill", function(d) { return d.active == "true" ? "black" : "gray";})
      .text(function(d) {
        return d.value ? d.name + " (" + d.value + ")" : d.name;
      })
      .style("fill-opacity", 1e-6);

  // Transition nodes to their new position.
  var nodeUpdate = node.transition()
      .duration(duration)
      .attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; });

  nodeUpdate.select("circle")
      .attr("r", 5)
      .style("fill", function(d) { return d._children ? "red" : "#fff"; });

  nodeUpdate.select("text")
      .style("fill-opacity", 1);

  // Transition exiting nodes to the parent's new position.
  var nodeExit = node.exit().transition()
      .duration(duration)
      .attr("transform", function(d) { return "translate(" + source.y + "," + source.x + ")"; })
      .remove();

  nodeExit.select("circle")
      .attr("r", 1e-6);

  nodeExit.select("text")
      .style("fill-opacity", 1e-6);

  // Update the links…
  var link = svg.selectAll("path.link")
      .data(links, function(d) { return d.target.id; });

  // Enter any new links at the parent's previous position.
  link.enter().insert("path", "g")
      .attr("class", "link")
      .attr("d", function(d) {
        var o = {x: source.x0, y: source.y0};
        return diagonal({source: o, target: o});
      });

  // Transition links to their new position.
  link.transition()
      .duration(duration)
      .attr("d", diagonal);

  // Transition exiting nodes to the parent's new position.
  link.exit().transition()
      .duration(duration)
      .attr("d", function(d) {
        var o = {x: source.x, y: source.y};
        return diagonal({source: o, target: o});
      })
      .remove();

  // Stash the old positions for transition.
  nodes.forEach(function(d) {
    d.x0 = d.x;
    d.y0 = d.y;
  });
}

// Toggle children on click.
function click(d) {

  var i = 0;
  var mynode;

  // find element in our json files (metrics, attributes of quality).
  if (typeof d.type == "undefined") {
    alert("No type defined on node.");
  } else {
    if (d.type == "metric") {
      mynode = d;
      mynode.description = mymetrics[d.mnemo]["description"];
      mynode.name = mymetrics[d.mnemo]["name"];
      mynode.datasource = mymetrics[d.mnemo]["ds"];
      var mydiv = d3.select("div#details-box");

      mydiv.text("");

      var ptitle = mydiv.append('p');
      ptitle.classed("title", true);
      ptitle.text(d.type.charAt(0).toUpperCase() + d.type.slice(1) + ": " + mynode.name + " (" + mynode.mnemo + ")");

      p = mydiv.append('p');
      ptitle = p.append('span');
      ptitle.classed("details-title", true);
      ptitle.text("Active:")
      pactive = p.append('span');
      pactive.classed("details", true);
      pactive.text(mynode.active.charAt(0).toUpperCase() + mynode.active.slice(1));

      p = mydiv.append('p');
      ptitle = p.append('span');
      ptitle.classed("details-title", true);
      ptitle.text("Data source:")
      psource = ptitle.append('span');
      psource.classed("details", true);
      psource.text(mynode.datasource);

      pdesct = mydiv.append('p');
      pdesct.classed("details-title", true);
      pdesct.text("Description:");

      var pdesc = mydiv.append('p');
      pdesc.classed("details", true);
      pdesc.html(mynode.description);
    } else if (d.type == "attribute") {
      mynode = d;
      mynode.description = myattrs[d.mnemo]["description"];
      mynode.name = myattrs[d.mnemo]["name"];

      var mydiv = d3.select("div#details-box");

      mydiv.text("");

      var ptitle = mydiv.append('p');
      ptitle.classed("title", true);
      ptitle.text(d.type.charAt(0).toUpperCase() + d.type.slice(1) + ": " + mynode.name + " (" + mynode.mnemo + ")");

      var pactive = mydiv.append('p');
      ptitle = pactive.append('span');
      ptitle.classed("details-title", true);
      ptitle.text("Active:");
      pactive = pactive.append('span');
      pactive.classed("details", true);
      pactive.text(mynode.active);

      pdesct = mydiv.append('p');
      pdesct.classed("details-title", true);
      pdesct.html("<b>Description:</b>")
      var pdesc = mydiv.append('p');
      pdesc.classed("details", true);
      pdesc.text(mynode.description);
    }
  }
}

</script>

<div id="details-box"><p>Click on a node to get more details.</p></div>
