{% extends "basic_template.html" %}
{% block title %}
{{ super() }}
{% endblock %}
{% block head %}
{{ super() }}
{% endblock %}
{% block content %}

<script>
  function download_result() {
    const element = document.createElement('a');
    element.style.display = 'none';
    
    const data = document.getElementsByName("model_result")[0].value;
    element.setAttribute('href', 'data:text/comma-separated-values;charset=utf-8,' + encodeURIComponent(data));
    element.setAttribute('download', 'model_results.csv');
    document.body.appendChild(element);
    element.click();
    document.body.removeChild(element);
  }
</script>

<h1>Results</h1>


<div class="w3-row-padding">
  <div class="w3-container w3-margin w3-border-large">
    <header class="w3-container w3-us-blue">
      {% if num_edge_lists == 1 %}
      <h3>Trajectory</h3>
      {% else %}
      <h3>Trajectories</h3>
      {% endif %}
    </header>
    {% for edge_list, return_state, source_labels, count, variable_level_plot in trajectories %}
    <div style="overflow-x: auto">
      <table class="w3-table-all w3-centered  w3-hoverable">
        <tr class="w3-us-blue">
          <th class="w3-us-red" style="position: absolute; width: 4em; left: 0;">State</th>
          {% for variable in variables %}
          <th>{{ variable }}</th>
          {% endfor %}
        </tr>
        {% for edge in edge_list %}
        <tr>
          <td class="w3-us-red" style="position: absolute; width: 4em; left: 0;">{{ source_labels[loop.index0] }}</td>
          {% for variable in variables %}
          <td style="background-color:{{ {0: "#e5e5e5", 1: "#adadad", 2:"#636363"}[edge['source'][variable]] }}">{{ edge['source'][variable] }}</td>
          {% endfor %}
        </tr>
        {% endfor %}
        <tr>
          <td class="w3-us-blue" style="position: absolute; width: 4em; left: 0;">{{ return_state }}*</td>
          {% for variable in variables %}
          <td style="background-color:{{ {0: "#e5e5e5", 1: "#adadad", 2:"#636363"}[edge_list[-1]['target'][variable]] }}">{{ edge_list[-1]['target'][variable] }}</td>
          {% endfor %}
        </tr>
      </table>
      <div class="w3-container w3-us-red"><div class="w3-half w3-center">Returns to state {{ return_state }}</div>
	                                      <div class="w3-half w3-center">Count {{ count }}</div></div>
    </div>
    <hr>
    <center>{{ variable_level_plot }}</center>
    <hr>
    {% endfor %}
    <center>
      <button class="w3-btn w3-us-red w3-margin w3-round" onclick="printElement('trajectory_graph')">Print Trajectory Graph</button><br>
      <div id="trajectory_graph"></div>
    </center>
  </div>

  <script>
    function printElement(elementId) {
      const contents = document.getElementById(elementId).outerHTML;
      const popupWindow = window.open('', '_blank', 'location=no,menubar=no,scrollbars=no,status=no,toolbar=no');
      popupWindow.document.open();
      popupWindow.document.write('<html><head><style></style></head><body onload="window.print()">' + contents + '</html>');
      popupWindow.document.close();
    }
  </script>

<textarea name="model_result" style="display: none;">
{% for edge_list, return_state, source_labels, count, variable_level_plot in trajectories %}
Count,{{ count }}
,{{variables|join(',') }}
{% for edge in edge_list %}{{ source_labels[loop.index0] }},{% for variable in variables %}{{ edge['source'][variable] }}{{ "," if not loop.last else "" }}{% endfor %}
{% endfor %}{{ return_state }},{% for variable in variables %}{{ edge_list[-1]['target'][variable] }}{{ "," if not loop.last else "" }}{% endfor %}
{% endfor %}
</textarea>
<input class="w3-btn w3-us-red w3-margin w3-round"
       value="Download csv"
       onclick="download_result()">

<script src="{{ url_for('static', filename='d3.v6.min.js') }}"></script>
<script src="{{ url_for('static', filename='d3-force.v2.min.js') }}"></script>
<script>

data = {"nodes":{{ nodes|safe }},
        "links":{{ links|safe }}}

var height = {{ height_px }};
var width = {{ width_px }};

const links = data.links.map(d => Object.create(d));
const nodes = data.nodes.map(d => Object.create(d));

const simulation = d3.forceSimulation(nodes)
    .force("link", d3.forceLink(links).id(d => d.id))
    .force("center", d3.forceCenter().strength(0.5))
    .force("charge", d3.forceManyBody())
    .alpha(0.5)
    .alphaDecay(0.005)
    .force("x", d3.forceX())
    .force("y", d3.forceY());

const svg = d3.select("#trajectory_graph")
    .append("svg")
    .attr("xmlns","http://www.w3.org/2000/svg")
    .attr("viewBox", [-width / 2, -height / 2, width, height])
    .attr('xoverflow','visible')
    .attr("width", "100%")
    .attr("style", "height: {{ height_percent }}vh;");

// create an arrowhead "template"
svg.append("defs")
   .append("marker")
   .attr('id', 'arrow')
   .attr('viewBox', '0 0 10 10')
   .attr('refX', 15)
   .attr('refY', 5)
   .attr('orient', 'auto-start-reverse')
   .attr('markerWidth', 6)
   .attr('markerHeight', 6)
   .attr('xoverflow','visible')
   .append('svg:path')
   .attr('d', 'M 0 0 L 10 5 L 0 10 z');

const link = svg.append("g")
    .attr("stroke", "#666")
    .attr("stroke-opacity", 0.9)
    .selectAll("line")
    .data(links)
    .join("line")
    .attr("stroke-width", 1.5)
    .attr("marker-end", "url(#arrow)");


var drag = simulation => {

  function dragstarted(event, d) {
    if (!event.active) simulation.alphaTarget(0.3).restart();
    d.fx = d.x;
    d.fy = d.y;
  }

  function dragged(event,d) {
    d.fx = event.x;
    d.fy = event.y;
  }

  function dragended(event,d) {
    if (!event.active) simulation.alphaTarget(0);
    d.fx = null;
    d.fy = null;
  }

  return d3.drag()
      .on("start", dragstarted)
      .on("drag", dragged)
      .on("end", dragended);
};

var color = () => {
  const scale = d3.scaleOrdinal(['#1f58b4', '#ff7f0e', '#2ca02c', '#d62728']).domain([0,1,2]);
  return d => scale(d.group);
}

const node = svg.append("g")
    .attr("stroke", "#fff")
    .attr("stroke-width", 1.5)
    .selectAll("circle")
    .data(nodes)
    .join("circle")
    .attr("r", d => d.radius ? 5 + d.radius / 3 : 5)
    .attr("fill", color())
    .call(drag(simulation));

node.append("title")
    .text(function(d) { return d.id });

simulation.on("tick", () => {
  link
      .attr("x1", d => d.source.x)
      .attr("y1", d => d.source.y)
      .attr("x2", d => d.target.x)
      .attr("y2", d => d.target.y);

  node
      .attr("cx", d => d.x)
      .attr("cy", d => d.y);

  svg.attr("viewBox", [Math.min(-100,d3.min(nodes.map(d => d.x))-10),
                       Math.min(-100,d3.min(nodes.map(d => d.y))-10),
                       Math.max(200,d3.max(nodes.map(d => d.x))-d3.min(nodes.map(d => d.x))+20),
                       Math.max(200,d3.max(nodes.map(d => d.y))-d3.min(nodes.map(d => d.y))+20),
                       ])
});


</script>
</div>

{% endblock %}
