{#
  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 title %}Airflow - DAGs{% endblock %}

{% block head_css %}
{{ super() }}
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='css/tree.css') }}">
{% endblock %}

{% block content %}
{{ super() }}
<div style="float: left" class="form-inline">
  <form method="get" style="float:left;">
    Base date: {{ form.base_date(class_="form-control") }}
    Number of runs: {{ form.num_runs(class_="form-control") }}
    <input type="hidden" name="root" value="{{ root if root else '' }}">
    <input type="hidden" value="{{ dag.dag_id }}" name="dag_id">
    <input type="submit" value="Go" class="btn btn-default"
                                    action="" method="get">
    <input name="_csrf_token" type="hidden" value="{{ csrf_token() }}">
  </form>
</div>
<div style="clear: both;"></div>
<hr/>
<div>
  <div class="legend_item" style="border: none;">no_status</div>
  <div class="square" style="background: white;"></div>
  <div class="legend_item" style="border: none;">queued</div>
  <div class="square" style="background: grey;"></div>
  <div class="legend_item" style="border: none;">up_for_retry</div>
  <div class="square" style="background: gold;"></div>
  <div class="legend_item" style="border: none;">up_for_reschedule</div>
  <div class="square" style="background: turquoise;"></div>
  <div class="legend_item" style="border: none;">upstream_failed</div>
  <div class="square" style="background: orange;"></div>
  <div class="legend_item" style="border: none;">skipped</div>
  <div class="square" style="background: pink;"></div>
  <div class="legend_item" style="border: none;">failed</div>
  <div class="square" style="background: red;"></div>
  <div class="legend_item" style="border: none;">running</div>
  <div class="square" style="background: lime;"></div>
  <div class="legend_item" style="border: none;">success</div>
  <div class="square" style="background: green;"></div>
  {% for op in operators %}
  <div class="legend_circle" style="background:{{ op.ui_color }};">
  </div>
  <div class="legend_item" style="float:left;border-color:white;">{{ op.task_type }}</div>
  {% endfor %}
  <div style="clear:both;"></div>
</div>
<hr/>
<div id="svg_container">
  <img id='loading' width="50" src="{{ url_for('static', filename='loading.gif') }}">
  <svg class='tree' width="100%">
    <filter id="blur-effect-1">
      <feGaussianBlur stdDeviation="3"></feGaussianBlur>
    </filter>
  </svg>
</div>
{% endblock %}

{% block tail %}
{{ super() }}
<script src="{{ url_for_asset('d3.min.js') }}"></script>
<script src="{{ url_for_asset('d3-tip.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.operator === 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 }}');
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("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("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("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": "0"})
      .attr("ry", function(d) {return is_dag_run(d)? "5": "0"})
      .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>
<script src="{{ url_for_asset('task-instances.js') }}"></script>
{% endblock %}
