{# 
  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" %}
{% import 'admin/lib.html' as lib with context %}
{% import 'admin/static.html' as admin_static with context %}

{% block title %}Airflow - DAGs{% endblock %}

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

{% block body %}
{{ super() }}
    {% if dag.doc_md %}
        <div class="rich_doc" style="margin-bottom: 15px;">{{ doc_md|safe }}</div>
    {% endif %}
    <div class="form-inline">
        <form method="get" style="float:left;">
            {{ state_token }}
            Run:
            {{ form.execution_date(class_="form-control") | safe }}
            Layout:
            {{ form.arrange(class_="form-control") | safe }}
            <input type="hidden" name="root" value="{{ root }}">
            <input type="hidden" value="{{ dag.dag_id }}" name="dag_id">
            <input name="_csrf_token" type="hidden" value="{{ csrf_token() }}">
            <input type="submit" value="Go" class="btn btn-default"
            action="" method="get">
        </form>
            <div class="input-group" style="float: right;">
              <input type="text" id="searchbox" class="form-control" placeholder="Search for..." onenter="null">
            </div><!-- /input-group -->
        <div style="clear: both;">
    </div>
<hr/>
<div>
    {% for op in operators %}
    <div class="legend_item" style="border-width:1px;float:left;background:{{ op.ui_color }};color:{{ op.ui_fgcolor }};">
        {{ op.__name__ }}
    </div>
    {% endfor %}

    <div style"background-color: blue;">
    <div class="legend_item state" style="border-color:white;">no status</div>
    <div class="legend_item state" style="border-color:grey;">queued</div>
    <div class="legend_item state" style="border-color:gold;">retry</div>
    <div class="legend_item state" style="border-color:pink;">skipped</div>
    <div class="legend_item state" style="border-color:red;">failed</div>
    <div class="legend_item state" style="border-color:lime;">running</div>
    <div class="legend_item state" style="border-color:green;">success</div>
    </div>
    <div style="clear:both;"></div>
</div>
<div id="error" style="display: none; margin-top: 10px;" class="alert alert-danger" role="alert">
        <span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>
        <span id="error_msg">Oops.</span>
</div>
<hr style="margin-bottom: 0px;"/>
<button class="btn btn-default pull-right" id="refresh_button">
    <span class="glyphicon glyphicon-refresh" aria-hidden="true"></span>
</button>
<div id="svg_container">

    <svg width="{{ width }}" height="{{ height }}">
        <g id='dig' transform="translate(20,20)"/>
        <filter id="blur-effect-1">
        <feGaussianBlur stdDeviation="3" />
        </filter>
    </svg>
    <img id="loading" alt="spinner" src="{{ url_for('static', filename='loading.gif') }}">
</div>
<hr>
{% endblock %}

{% block tail %}
    {{ super() }}

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

    var highlight_color = "#000000";
    var upstream_color = "#2020A0";
    var downstream_color = "#0000FF";

    var nodes = {{ nodes|safe }};
    var edges = {{ edges|safe }};
    var tasks = {{ tasks|safe }};
    var task_instances = {{ task_instances|safe }};
    var execution_date = "{{ execution_date }}";
    var arrange = "{{ arrange }}";
    var g = dagreD3.json.decode(nodes, edges);
    var duration = 500;
    var stateFocusMap = {
        'no status':false, 'failed':false, 'running':false,
        'queued': false, 'success': false};


    var layout = dagreD3.layout().rankDir(arrange).nodeSep(15).rankSep(15);
    var renderer = new dagreD3.Renderer();
    renderer.layout(layout).run(g, d3.select("#dig"));
    inject_node_ids(tasks);
    update_nodes_states(task_instances);

    d3.selectAll("g.node").on("click", function(d){
        task = tasks[d];
        if (task.task_type == "SubDagOperator")
            call_modal(d, execution_date, true);
        else
            call_modal(d, execution_date);
    });


    function highlight_nodes(nodes, color) {
        nodes.forEach (function (nodeid) {
            my_node = d3.select('#' + nodeid + ' rect');
            my_node.style("stroke", color) ;
        })
    }

    d3.selectAll("g.node").on("mouseover", function(d){
        d3.select(this).selectAll("rect").style("stroke", highlight_color) ;
        highlight_nodes(g.predecessors(d), upstream_color)
        highlight_nodes(g.successors(d), downstream_color)

    });

    d3.selectAll("g.node").on("mouseout", function(d){
        d3.select(this).selectAll("rect").style("stroke", null) ;
        highlight_nodes(g.predecessors(d), null)
        highlight_nodes(g.successors(d), null)
    });


    {% if blur %}
    d3.selectAll("text").attr("class", "blur");
    {% endif %}

    $("g.node").tooltip({
      html: true,
      container: "body",
    });

    d3.selectAll("div.legend_item.state")
        .style("cursor", "pointer")
        .on("mouseover", function(){
            if(!stateIsSet()){
                state = d3.select(this).text();
                focusState(state);
            }
        })
        .on("mouseout", function(){
            if(!stateIsSet()){
                clearFocus();
            }
        });

    d3.selectAll("div.legend_item.state")
        .on("click", function(){
            state = d3.select(this).text();
            color = d3.select(this).style("border-color");

            if (!stateFocusMap[state]){
                clearFocus();
                focusState(state, this, color);
                setFocusMap(state);

            } else {
                clearFocus();
                setFocusMap();
            }
        });

    d3.select("#searchbox").on("keyup", function(){
        var s = document.getElementById("searchbox").value;
        var match = null;

        if (stateIsSet){
            clearFocus();
            setFocusMap();
        }

        d3.selectAll("g.nodes g.node").filter(function(d, i){
            if (s==""){
                d3.select("g.edgePaths")
                    .transition().duration(duration)
                    .style("opacity", 1);
                d3.select(this)
                    .transition().duration(duration)
                    .style("opacity", 1)
                    .selectAll("rect")
                    .style("stroke-width", "2px");
            }
            else{
                d3.select("g.edgePaths")
                    .transition().duration(duration)
                    .style("opacity", 0.2);
                if (d.indexOf(s) > -1) {
                    if (!match)
                        match = this;
                    d3.select(this)
                        .transition().duration(duration)
                        .style("opacity", 1)
                        .selectAll("rect")
                        .style("stroke-width", "10px");
                }
                else {
                    d3.select(this)
                        .transition()
                        .style("opacity", 0.2).duration(duration)
                        .selectAll("rect")
                        .style("stroke-width", "2px");
                }
            }
        });
        if(match) {
            var transform = d3.transform(d3.select(match).attr("transform"));
            transform.translate = [
                -transform.translate[0] + 520,
                -(transform.translate[1] - 400)
            ];
            transform.scale = [1, 1];

            d3.select("g.zoom")
                .transition()
                .attr("transform", transform.toString());
            renderer.zoom_obj.translate(transform.translate);
            renderer.zoom_obj.scale(1);
        }
    });


    // Injecting ids to be used for parent/child highlighting
    // Separated from update_node_states since it must work even
    // when there is no valid task instance available
    function inject_node_ids(tasks) {
        $.each(tasks, function(task_id, task) {
            $('tspan').filter(function(index) { return $(this).text() === task_id; })
                    .parent().parent().parent()
                    .attr("id", task_id);
        });
    }


    // Assigning css classes based on state to nodes
    function update_nodes_states(task_instances) {
        $.each(task_instances, function(task_id, ti) {
          $('tspan').filter(function(index) { return $(this).text() === task_id; })
            .parent().parent().parent()
            .attr("class", "node enter " + ti.state)
            .attr("data-toggle", "tooltip")
            .attr("data-original-title", function(d) {
              // Tooltip
              task = tasks[task_id];
              tt =  "Task_id: " + ti.task_id + "<br>";
              tt += "Run: " + ti.execution_date + "<br>";
              if(ti.run_id != undefined){
                tt += "run_id: <nobr>" + ti.run_id + "</nobr><br>";
              }
              tt += "Operator: " + task.task_type + "<br>";
              tt += "Started: " + ti.start_date + "<br>";
              tt += "Ended: " + ti.end_date + "<br>";
              tt += "Duration: " + ti.duration + "<br>";
              tt += "State: " + ti.state + "<br>";
              return tt;
            });
        });
    }

    function clearFocus(){
        d3.selectAll("g.node")
            .transition(duration)
            .style("opacity", 1);
        d3.selectAll("g.node rect")
            .transition(duration)
            .style("stroke-width", "2px");
        d3.select("g.edgePaths")
            .transition().duration(duration)
            .style("opacity", 1);
        d3.selectAll("div.legend_item.state")
            .style("background-color", null);
    }

    function focusState(state, node, color){
        d3.selectAll("g.node")
            .transition(duration)
            .style("opacity", 0.2);
        d3.selectAll("g.node."+state)
            .transition(duration)
            .style("opacity", 1);
        d3.selectAll("g.node." + state + " rect")
            .transition(duration)
            .style("stroke-width", "10px")
            .style("opacity", 1);
        d3.select("g.edgePaths")
            .transition().duration(duration)
            .style("opacity", 0.2);
        d3.select(node)
            .style("background-color", color);
    }

    function setFocusMap(state){
        for (var key in stateFocusMap){
                stateFocusMap[key] = false;
        }
        if(state != null){
            stateFocusMap[state] = true;
        }
    }

    function stateIsSet(){
        for (var key in stateFocusMap){
            if (stateFocusMap[key]){
                return true
            }
        }
        return false
    }

    function error(msg){
      $('#error_msg').html(msg);
      $('#error').show();
      $('#loading').hide();
      $('#chart_section').hide(1000);
      $('#datatable_section').hide(1000);
    }

    d3.select("#refresh_button").on("click",
        function() {
            $("#loading").css("display", "block");
            $("div#svg_container").css("opacity", "0.2");
            $.get(
                "/admin/airflow/object/task_instances",
                {dag_id : "{{ dag.dag_id }}", execution_date : "{{ execution_date }}"})
            .done(
                function(task_instances) {
                    update_nodes_states(JSON.parse(task_instances));
                    $("#loading").hide();
                    $("div#svg_container").css("opacity", "1");
                    $('#error').hide();
                }
            ).fail(function(jqxhr, textStatus, err) {
                error(textStatus + ': ' + err);
            });
        }
    );

    </script>


{% endblock %}
