<h3>Transaction Trends</h3>
{% if (unique_transactions is defined) and unique_transactions %}

<div class="clearfix" style="margin-bottom:2em;">
  <div id="dTransactionTrends" class="graph" style="height:300px;background:#eee;"></div>
</div>
<script type="text/javascript">
appendOnLoad(function() {
  var data = {{ unique_transactions | batch(5) | first | tojson }};
  graphTrends(d3.select('#dTransactionTrends'), data, window.results_colors,
    (group) => group.name, // name of bar group
    (group) => group.results, // list of bars under group
    (child) => child.id, // id of bar
    (child) => child.name, // name of bar
    (bar) => (bar.elements.length > 0 ? bar.elements[0].aggregate.percentile95 : 0)
  )
})
</script>
<script type="text/javascript">
function graphTrends(el, data, subgroup_colors, fGroupName, fGroupChildren, fChildId, fChildName, fChildValue) {
  // set the dimensions and margins of the graph
  var margin = {top: 10, right: 30, bottom: 20, left: 50},
      width = getWH(el).width - margin.left - margin.right,
      height = getWH(el).height - margin.top - margin.bottom;

  // append the svg object to the body of the page
  var svg = el
    .append("svg")
      .attr("width", width + margin.left + margin.right)
      .attr("height", height + margin.top + margin.bottom)
    .append("g")
      .attr("transform",
            "translate(" + margin.left + "," + margin.top + ")");

  var groups = data.map(fGroupName);
  var all_subgroup_ids = []
  var all_values = []
  data.forEach(d => {
    var children = fGroupChildren(d)
    var mine = children.map(group => fChildId(group))
    var vals = children.map(group => parseFloat(fChildValue(group)));
    all_values = all_values.concat(vals)
    all_subgroup_ids = all_subgroup_ids.concat(mine)
  })
  var colors = subgroup_colors.map(g => g.color)
  var subgroups = all_subgroup_ids.filter( onlyUnique );

  var max_y_value = Math.max.apply(Math, all_values);

  var x = d3.scaleBand()
      .domain(groups)
      .range([0, width])
      .padding([0.2])
  svg.append("g")
    .attr("transform", "translate(0," + height + ")")
    .call(d3.axisBottom(x).tickSize(0));

    // Add Y axis
   var y = d3.scaleLinear()
     .domain([0, max_y_value])
     .range([ height, 0 ]);
   svg.append("g")
     .call(d3.axisLeft(y));

   // Another scale for subgroup position?
   var xSubgroup = d3.scaleBand()
     .domain(subgroups)
     .range([0, x.bandwidth()])
     .padding([0.05])

   // color palette = one color per subgroup
   var color = d3.scaleOrdinal()
     .domain(subgroups)
     .range(colors)

  var getSubgroupValue = function(this_group_data, bar_id) {
    var children = fGroupChildren(this_group_data)
    var results = children.filter(child => fChildId(child) === bar_id)
    var value = fChildValue(results[0])
    return value
  }
  var setupBarData = function(d) {
    return subgroups.map(function(key) {
      return {
        key: key,
        data: d,
        value: getSubgroupValue(d,key)
      };
    });
  }

   var gs = svg.append("g")
     .selectAll("g")
     // Enter in data = loop group per group
     .data(data)
     .enter()
     .append("g")
       .attr("transform", function(d) { return "translate(" + x(fGroupName(d)) + ",0)"; })
       .text(function(d) { return fGroupName(d) })
   gs
     .selectAll("rect")
     .data(setupBarData)
     .enter()
     .append("rect")
       .attr("x", function(d) { return xSubgroup(d.key); })
       .attr("y", function(d) { return y(d.value); })
       .attr("width", xSubgroup.bandwidth())
       .attr("height", function(d) { return height - y(d.value); })
       .attr("fill", function(d) { return color(d.key); })
       .on("mouseover", handleMouseOverBar)
       .on("mouseout", handleMouseOutBar);
   texts = gs
   .selectAll("text")
   .data(setupBarData)
   .enter()
   texts
   .append("text")
     .attr("x", function(d) { return xSubgroup(d.key); })
     .attr("y", function(d) { return getWH(el).height-60 }) //y(d.value); })
     .attr("width", xSubgroup.bandwidth())
     .attr("dx", (xSubgroup.bandwidth()/2)+"px")
     .attr("dy", "1.75em")
     .text(function(d) { return subgroup_colors.filter(g => g.id===d.key).map(g => g.index)[0] })
   texts
   .append("text")
     .attr("x", function(d) { return xSubgroup(d.key); })
     .attr("y", function(d) { return Math.min(y(d.value),getWH(el).height-100) }) //y(d.value); })
     .attr("width", xSubgroup.bandwidth())
     .attr("dx", ((xSubgroup.bandwidth()/2)-20)+"px")
     .attr("dy", "1.75em")
     .text(function(d) { console.log(y(d.value));return d.value })

}

function onlyUnique(value, index, self) {
    return self.indexOf(value) === index;
}

function getCell(d,i) {
  var bar_id = d.key;
  var index = window.results_colors.filter(r => r.id === bar_id)[0].index;
  var groupName = d.data.name;
  return d3.selectAll('*[data-transaction-name = "'+groupName+'"][data-result-id = "'+bar_id+'"]')
}
function handleMouseOverBar(d, i) {
  var cell = getCell(d,i)
  cell.style("background-color","yellow")
}
function handleMouseOutBar(d, i) {
  var cell = getCell(d,i)
  cell.style("background-color","transparent")
}
</script>

<table>
<thead>
<tr>
<td>Transaction Name</td>
<td>Max Avg Dur</td>
<td>Max p95</td>
<td>Max p99</td>
{% for result in results | sort(attribute='startDate') %}
<td>({{result.index}}) p95</td>
{% endfor %}
</tr>
</thead>
<tbody>
{% for group in unique_transactions | sort(attribute='max_percentile95',reverse=true) %}
<tr>
<td>{{group.name}}</td>
<td>{{group.aggregate.max_avgDuration}}</td>
<td>{{group.aggregate.max_percentile95}}</td>
<td>{{group.aggregate.max_percentile99}}</td>
{% for r in results | sort(attribute='startDate') %}
<td id="td_pN_{{r.id}}" data-transaction-name="{{group.name}}" data-result-id="{{r.id}}">
{% for result in group.results | selectattr('id', 'equalto', r.id) %}
{% if result.elements|length > 0 %}{{result.elements[0].aggregate.percentile95}}{% else %}0{% endif %}
{% endfor %}
<script type="text/javascript">
d3.selectAll("#td_pN_{{r.id}}")
    .style("color",window.results_colors[{{r.index}}].color)
</script>
</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>

{% else %}
    No transaction data in this test.
{% endif %}
