{#
 Licensed to the Apache Software Foundation (ASF) under one
 or more contributor license agreements.  See the NOTICE file
 distributed with this work for additional information
 regarding copyright ownership.  The ASF licenses this file
 to you under the Apache License, Version 2.0 (the
 "License"); you may not use this file except in compliance
 with the License.  You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing,
 software distributed under the License is distributed on an
 "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 KIND, either express or implied.  See the License for the
 specific language governing permissions and limitations
 under the License.
#}

{% extends "airflow/dag.html" %}
{% block page_title %}{{ dag.dag_id }} - Tree - Airflow{% endblock %}

{% block head_css %}
  {{ super() }}
  <link rel="stylesheet" type="text/css" href="{{ url_for_asset('tree.css') }}">
  <style type="text/css">
    {% for state, state_color in state_color_mapping.items() %}
      rect.{{state}} {
        fill: {{state_color}};
      }
    {% endfor %}
  </style>
{% endblock %}

{% block content %}
  {{ super() }}
  <div class="row dag-view-tools">
    <div class="col-md-12">
      <form method="get" class="form-inline">
        <input type="hidden" name="root" value="{{ root if root else '' }}">
        <input type="hidden" value="{{ dag.dag_id }}" name="dag_id">
        <input type="hidden" name="_csrf_token" value="{{ csrf_token() }}">
        <div class="form-group">
          <label class="sr-only" for="base_date">Base date</label>
          <div class="input-group">
            {{ form.base_date(class_="form-control", disabled=not(dag.has_dag_runs())) }}
          </div>
        </div>
        <div class="form-group">
          <label class="sr-only" for="num_runs">Number of runs</label>
          <div class="input-group">
            <div class="input-group-addon">Runs</div>
            {{ form.num_runs(class_="form-control", disabled=not(dag.has_dag_runs())) }}
          </div>
        </div>
        <button type="submit" class="btn"{{' disabled' if not dag.has_dag_runs() else ''}}>Update</button>
        {% if not dag.has_dag_runs() %}<span class="text-warning" style="margin-left:16px;">No DAG runs yet.</span>{% endif %}
      </form>
    </div>
  </div>
  <div class="legend-row">
    <div>
      {% for op in operators %}<span class="legend-item legend-item--no-border">
        <span class="legend-item__swatch legend-item__swatch--circle" style="background: {{ op.ui_color }};"></span>
        {{ op.task_type }}
      </span>{% endfor %}
    </div>
    <div>
      {% for state, state_color in state_color_mapping.items() %}<span class="legend-item legend-item--no-border">
        <span class="legend-item__swatch legend-item__swatch--no-border" style="background: {{ state_color }};"></span>
        {{state}}</span>{% endfor %}<span class="legend-item legend-item--no-border">
        <span class="legend-item__swatch"></span>no_status</span>
    </div>
  </div>
  <hr>
  <div id="svg_container">
    <img id='loading' width="50" src="{{ url_for('static', filename='loading.gif') }}">
    <svg id="tree-svg" class='tree' width="100%">
      <filter id="blur-effect-1">
        <feGaussianBlur stdDeviation="3"></feGaussianBlur>
      </filter>
    </svg>
  </div>
{% endblock %}

{% block tail_js %}
  {{ super() }}
  <script src="{{ url_for_asset('d3.min.js') }}"></script>
  <script src="{{ url_for_asset('d3-tip.js') }}"></script>
  <script src="{{ url_for_asset('taskInstances.js') }}"></script>
  <script>
    $('span.status_square').tooltip({html: true});

    function ts_to_dtstr(ts) {
      var dt = new Date(ts * 1000);
      return dt.toISOString();
    }

    function is_dag_run(d) {
      return d.run_id != undefined;
    }

    var now_ts = Date.now()/1000;

    function populate_taskinstance_properties(node) {
      // populate task instance properties for display purpose
      var j;
      for (j=0; j<node.instances.length; j++) {
        var dr_instance = data.instances[j];
        var row = node.instances[j];

        if (row === null) {
          node.instances[j] = {
            task_id: node.name,
            execution_date: dr_instance.execution_date,
          };
          continue;
        }

        var task_instance = {
          state: row[0],
          try_number: row[1],
          start_ts: row[2],
          duration: row[3],
        };
        node.instances[j] = task_instance;

        task_instance.task_id = node.name;
        task_instance.operator = node.operator;
        task_instance.execution_date = dr_instance.execution_date;
        task_instance.external_trigger = dr_instance.external_trigger;

        // compute start_date and end_date if applicable
        if (task_instance.start_ts !== null) {
          task_instance.start_date = ts_to_dtstr(task_instance.start_ts);
          if (task_instance.state === "running") {
            task_instance.duration = now_ts - task_instance.start_ts;
          } else if (task_instance.duration !== null) {
            task_instance.end_date = ts_to_dtstr(task_instance.start_ts + task_instance.duration);
          }
        }
      }
    }

    var devicePixelRatio = window.devicePixelRatio || 1;
    // JSON.parse is faster for large payloads than an object literal (because the JSON grammer is simpler!)
    var data = JSON.parse({{ data|tojson }});
    var barHeight = 20;
    var axisHeight = 40;
    var square_x = parseInt(500 * devicePixelRatio);
    var square_size = 10;
    var square_spacing = 2;
    var margin = {top: barHeight/2 + axisHeight, right: 0, bottom: 0, left: barHeight/2},
        width = parseInt(960 * devicePixelRatio) - margin.left - margin.right,
        barWidth = width * 0.9;

    var i = 0,
        duration = 400,
        root;

    var tree = d3.layout.tree().nodeSize([0, 25]);
    var nodes = tree.nodes(data);
    var nodeobj = {};
    for (i=0; i<nodes.length; i++) {
      var node = nodes[i];
      nodeobj[node.name] = node;

      if (node.name === "[DAG]") {
        // skip synthetic root node since it's doesn't contain actual task instances
        continue;
      }

      if (node.start_ts !== undefined) {
        node.start_date = ts_to_dtstr(node.start_ts);
      }
      if (node.end_ts !== undefined) {
        node.end_date = ts_to_dtstr(node.end_ts);
      }
      if (node.depends_on_past === undefined) {
        node.depends_on_past = false;
      }

      populate_taskinstance_properties(node);
    }

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

    const taskTip = d3.tip()
      .attr('class', 'tooltip d3-tip')
      .html(function(toolTipHtml) {
        return toolTipHtml;
    });

    var svg = d3.select("#tree-svg")
        //.attr("width", width + margin.left + margin.right)
      .append("g")
      .attr("class", "level")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

        data.x0 = 0;
        data.y0 = 0;

      if (nodes.length == 1)
        var base_node = nodes[0];
      else
        var base_node = nodes[1];

      var num_square = base_node.instances.length;
      var extent = d3.extent(base_node.instances, function(d,i) {
        return new Date(d.execution_date);
      });
      var xScale = d3.time.scale()
      .domain(extent)
      .range([
        square_size/2,
        (num_square * square_size) + ((num_square-1) * square_spacing) - (square_size/2)
      ]);

      d3.select("#tree-svg")
      .insert("g")
      .attr("transform",
        "translate("+ (square_x + margin.left) +", " + axisHeight + ")")
      .attr("class", "axis").call(
        d3.svg.axis()
        .scale(xScale)
        .orient("top")
        .ticks(2)
      )
      .selectAll("text")
      .attr("transform", "rotate(-30)")
      .style("text-anchor", "start").call(taskTip);

      function node_class(d) {
            var sclass = "node";
            if (d.children === undefined && d._children === undefined)
              sclass += " leaf";
            else {
              sclass += " parent";
              if (d.children === undefined)
                sclass += " collapsed"
              else
                sclass += " expanded"
            }
            return sclass;
      }

    update(root = data);

    function update(source) {

      // Compute the flattened node list. TODO use d3.layout.hierarchy.
      var nodes = tree.nodes(root);

      var height = Math.max(500, nodes.length * barHeight + margin.top + margin.bottom);
      var width = square_x + (num_square * (square_size + square_spacing)) + margin.left + margin.right + 50;
      d3.select("#tree-svg").transition()
          .duration(duration)
          .attr("height", height)
          .attr("width", width);

      d3.select(self.frameElement).transition()
          .duration(duration)
          .style("height", height + "px");

      // Compute the "layout".
      nodes.forEach(function(n, i) {
        n.x = i * barHeight;
      });

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

      var nodeEnter = node.enter().append("g")
      .attr("class", node_class)
      .attr("transform", function(d) {
        return "translate(" + source.y0 + "," + source.x0 + ")";
      })
      .style("opacity", 1e-6);

      nodeEnter.append("circle")
          .attr("r", (barHeight / 3))
          .attr("class", "task")
          .attr("data-toggle", "tooltip")
          .on("mouseover", function(d) {
            var tt = "";
            if (d.operator != undefined) {
              if (d.operator != undefined) {
                tt += "operator: " + escapeHtml(d.operator) + "<br>";
              }

              tt += "depends_on_past: " + escapeHtml(d.depends_on_past) + "<br>";
              tt += "upstream: " + escapeHtml(d.num_dep) + "<br>";
              tt += "retries: " + escapeHtml(d.retries) + "<br>";
              tt += "owner: " + escapeHtml(d.owner) + "<br>";
              tt += "start_date: " + escapeHtml(d.start_date) + "<br>";
              tt += "end_date: " + escapeHtml(d.end_date) + "<br>";
            }
            taskTip.direction('e')
            taskTip.show(tt, this)
            d3.select(this).transition()
             .style('stroke-width', 3)
          })
          .on('mouseout', function(d, i) {
            taskTip.hide(d)
            d3.select(this).transition()
             .style("stroke-width", function(d) {return is_dag_run(d)? "2": "1"})
          })
          .attr("height", barHeight)
          .attr("width", function(d, i) {return barWidth - d.y;})
          .style("fill", function(d) {return d.ui_color;})
          .attr("task_id", function(d){return d.name})
          .on("click", toggles);

      text = nodeEnter.append("text")
          .attr("dy", 3.5)
          .attr("dx", barHeight/2)
          .text(function(d) { return d.name; });
      {% if blur %}
      text.attr("class", "blur");
      {% endif %}

      nodeEnter.append('g')
          .attr("class", "stateboxes")
          .attr("transform",
            function(d, i) { return "translate(" + (square_x-d.y) + ",0)"; })
          .selectAll("rect").data(function(d) { return d.instances; })
          .enter()
          .append('rect')
          .on("click", function(d){
            if(d.task_id === undefined)
                call_modal_dag(d);
            else if(nodeobj[d.task_id].operator=='SubDagOperator')
                // I'm pretty sure that true is not a valid subdag id, which is what call_modal wants
                call_modal(d.task_id, d.execution_date, nodeobj[d.task_id].extra_links, d.try_number, true);
            else
                call_modal(d.task_id, d.execution_date, nodeobj[d.task_id].extra_links, d.try_number, undefined);
          })
          .attr("class", function(d) {return "state " + d.state})
          .attr("data-toggle", "tooltip")
          .attr("rx", function(d) {return is_dag_run(d)? "5": "1"})
          .attr("ry", function(d) {return is_dag_run(d)? "5": "1"})
          .style("shape-rendering", function(d) {return is_dag_run(d)? "auto": "crispEdges"})
          .style("stroke-width", function(d) {return is_dag_run(d)? "2": "1"})
          .style("stroke-opacity", function(d) {return d.external_trigger ? "0": "1"})
          .on("mouseover", function(d){
            var tt = tiTooltip(d);
            taskTip.direction('n');
            taskTip.show(tt, this);
            d3.select(this).transition()
             .style('stroke-width', 3)
          })
          .on('mouseout', function(d,i) {
            taskTip.hide(d)
            d3.select(this).transition()
             .style("stroke-width", function(d) {return is_dag_run(d)? "2": "1"})
          })
          .attr('x', function(d, i) {return (i*(square_size+square_spacing));})
          .attr('y', -square_size/2)
          .attr('width', 10)
          .attr('height', 10);


      // Transition nodes to their new position.
      nodeEnter.transition()
          .duration(duration)
          .attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; })
          .style("opacity", 1);

      node.transition()
          .duration(duration)
          .attr("class", node_class)
          .attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; })
          .style("opacity", 1);

      // Transition exiting nodes to the parent's new position.
      node.exit().transition()
          .duration(duration)
          .attr("transform", function(d) { return "translate(" + source.y + "," + source.x + ")"; })
          .style("opacity", 1e-6)
          .remove();

      // Update the links…
      var link = svg.selectAll("path.link")
          .data(tree.links(nodes), 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()
          .duration(duration)
          .attr("d", diagonal);

      // 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;
      });

      $('#loading').remove()
    }

    function toggles(clicked_d) {
        // Collapse nodes with the same task id
        d3.selectAll("[task_id='" + clicked_d.name + "']").each(function(d){
          if(clicked_d != d && d.children) {
              d._children = d.children;
              d.children = null;
            update(d);
          }
        });

        // Toggle clicked node
        if(clicked_d._children) {
            clicked_d.children = clicked_d._children;
            clicked_d._children = null;
        } else {
            clicked_d._children = clicked_d.children;
            clicked_d.children = null;
        }
        update(clicked_d);
    }
    // Toggle children on click.
    function click(d) {
      if (d.children || d._children){
        if (d.children) {
          d._children = d.children;
          d.children = null;
        } else {
          d.children = d._children;
          d._children = null;
        }
        update(d);
      }
    }
  </script>
{% endblock %}
