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

{% block title %}Airflow - DAG {{ dag.dag_id }}{% endblock %}

{% block head_css %}
  {{ lib.form_css() }}
  {{ super() }}
  <link href="{{ url_for("static", filename="bootstrap-toggle.min.css") }}" rel="stylesheet" type="text/css">
{% endblock %}

{% block body %}
  <div>
    <h3 class="pull-left">
      {% if dag.parent_dag %}
        <span style='color:#AAA;'>SUBDAG: </span> <span> {{ dag.dag_id }}</span>
      {% else %}
        <input id="pause_resume" dag_id="{{ dag.dag_id }}" type="checkbox" {{ "checked" if not dag.is_paused else "" }} data-toggle="toggle" data-size="mini" method="post">
        <span style='color:#AAA;'>DAG: </span> <span> {{ dag.dag_id }}</span> <small class="text-muted"> {{ dag.description }} </small>
      {% endif %}
      {% if root %}
        <span style='color:#AAA;'>ROOT: </span> <span> {{ root }}</span>
      {% endif %}
    </h3>
    <h4 class="pull-right">
      <a class="label label-default" href="{{ url_for('dagrun.index_view') }}?_flt_2_dag_id={{ dag.dag_id }}">
        schedule: {{ dag.schedule_interval }}
      </a>
    </h4>
  </div>
  <div class="clearfix"></div>
  <div>
    <ul class="nav nav-pills">
      {% if dag.parent_dag %}
          <li class="never_active"><a href="{{ url_for('airflow.' + dag.get_default_view(), dag_id=dag.parent_dag.dag_id) }}">
              <span class="glyphicon glyphicon-arrow-left" aria-hidden="true"></span>
              Back to {{ dag.parent_dag.dag_id }}</a>
          </li>
      {% endif %}
      <li><a href="{{ url_for("airflow.graph", dag_id=dag.dag_id, root=root, execution_date=execution_date) }}">
          <span class="glyphicon glyphicon-certificate" aria-hidden="true"></span>
        Graph View</a></li>
      <li><a href="{{ url_for("airflow.tree", dag_id=dag.dag_id, num_runs=num_runs, root=root) }}">
          <span class="glyphicon glyphicon-tree-deciduous" aria-hidden="true"></span>
        Tree View
      </a></li>
      <li><a href="{{ url_for("airflow.duration", dag_id=dag.dag_id, days=30, root=root) }}">
          <span class="glyphicon glyphicon-stats" aria-hidden="true"></span>
          Task Duration
      </a></li>
      <li><a href="{{ url_for("airflow.tries", dag_id=dag.dag_id, days=30, root=root) }}">
          <span class="glyphicon glyphicon-duplicate" aria-hidden="true"></span>
          Task Tries
      </a></li>
      <li>
        <a href="{{ url_for("airflow.landing_times", dag_id=dag.dag_id, days=30, root=root) }}">
          <span class="glyphicon glyphicon-plane" aria-hidden="true"></span>
          Landing Times
        </a>
      </li>
      <li>
        <a href="{{ url_for("airflow.gantt", dag_id=dag.dag_id, root=root) }}">
          <span class="glyphicon glyphicon-align-left" aria-hidden="true"></span>
          <i class="icon-align-left"></i>
          Gantt
        </a>
      </li>
      <li>
      <a href="{{ url_for("airflow.dag_details", dag_id=dag.dag_id) }}">
          <span class="glyphicon glyphicon-list" aria-hidden="true"></span>
          Details
        </a>
      </li>
      <li>
        <a href="{{ url_for("airflow.code", dag_id=dag.dag_id, root=root) }}">
          <span class="glyphicon glyphicon-file" aria-hidden="true"></span>
          Code
        </a>
      </li>
      <li>
        <a href="{{ url_for("airflow.trigger", dag_id=dag.dag_id, origin=url_for("airflow.tree", dag_id=dag.dag_id)) }}"
          onclick="return confirmTriggerDag(this, '{{ dag.safe_dag_id }}')">
          <span class="glyphicon glyphicon-play-circle" aria-hidden="true"></span>
          Trigger DAG
        </a>
      </li>
      <li>
        <a href="{{ url_for("airflow.refresh", dag_id=dag.dag_id) }}" title="Refresh" onclick="postAsForm(this.href); return false">
          <span class="glyphicon glyphicon-refresh" aria-hidden="true"></span>
          Refresh
        </a>
      </li>
      <li>
        <a href="{{ url_for("airflow.delete", dag_id=dag.dag_id, root=root) }}"
        onclick="return confirmDeleteDag(this, '{{ dag.safe_dag_id }}')">
        <span class="glyphicon glyphicon-remove-circle" style="color:red" aria-hidden="true"></span>
        Delete
        </a>
      </li>
    </ul>
  </div>
  <hr>
  <!-- Modal -->
  <div class="modal fade" id="myModal"
        tabindex="-1" role="dialog"
      aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h4 class="modal-title" id="myModalLabel">
            <span id='task_id'></span>
            <button id="btn_filter" type="button" class="btn btn-default" title="Filter on this task and upstream ">
              <span class="glyphicon glyphicon-filter" style="margin-left: 0px;" aria-hidden="true"></span>
            </button>
              on
            <span id='execution_date'></span>
          </h4>
        </div>
        <div class="modal-body">
          <div id="div_btn_subdag">
              <button id="btn_subdag" type="button" class="btn btn-primary">
                Zoom into Sub DAG
              </button>
              <hr/>
          </div>
          <button id="btn_task" type="button" class="btn btn-primary">
            Task Instance Details
          </button>
          <button id="btn_rendered" type="button" class="btn btn-primary">
            Rendered
          </button>
          <button id="btn_ti" type="button" class="btn btn-primary">
            Task Instances
          </button>
          <button id="btn_log" type="button" class="btn btn-primary">
            View Log
          </button>
          <hr/>
          <div id="dag_dl_logs">
            <label style="display:inline"> Download Log (by attempts): </label>
            <ul class="nav nav-pills" role="tablist" id="try_index" style="display:inline">
            </ul>
            <hr/>
          </div>
          <div id="dag_es_logs">
            <label style="display:inline"> View Logs in Elasticsearch (by attempts): </label>
            <ul class="nav nav-pills" role="tablist" id="es_try_index" style="display:inline">
            </ul>
            <hr/>
            <hr/>
          </div>
          <form method="POST">
            <input name="csrf_token" type="hidden" value="{{ csrf_token() }}"/>
            <input name="dag_id" type="hidden">
            <input name="task_id" type="hidden">
            <input name="execution_date" type="hidden">
            <input name="origin" type="hidden" value="{{ request.base_url }}">
            <button id="btn_run" type="button" class="btn btn-primary"
              title="Runs a single task instance"
              data-action="{{ url_for('airflow.run') }}">
              Run
            </button>
            <span class="btn-group" data-toggle="buttons">
              <label
                class="btn"
                title="Ignores all non-critical dependencies, including task state and task_deps">
                <input type="checkbox" value="true" name="ignore_all_deps" autocomplete="off">
                Ignore All Deps</label>
              <label class="btn"
                title="Ignore previous success/failure">
                <input type="checkbox" value="true" name="ignore_ti_state" autocomplete="off">
                Ignore Task State
              </label>
              <label class="btn"
                title="Disregard the task-specific dependencies, e.g. status of upstream task instances and depends_on_past">
                <input type="checkbox" value="true" name="ignore_task_deps" autocomplete="off">
                Ignore Task Deps
              </label>
            </span>
            <hr/>
            <button id="btn_clear" type="button" class="btn btn-primary"
                title="Clearing deletes the previous state of the task instance, allowing it to get re-triggered by the scheduler or a backfill command"
                data-action="{{ url_for('airflow.clear') }}"
                >Clear
            </button>
            <span class="btn-group" data-toggle="buttons">
              <label class="btn"
                title="Also include past task instances when clearing this one">
                <input type="checkbox" value="true" name="past" autocomplete="off">
                Past
              </label>
              <label class="btn"
                title="Also include future task instances when clearing this one">
                <input type="checkbox" value="true" name="future" autocomplete="off">
                Future
              </label>
              <label class="btn"
                title="Also include upstream dependencies">
                <input type="checkbox" value="true" name="upstream" autocomplete="off">
                Upstream
              </label>
              <label class="btn active"
                title="Also include downstream dependencies">
                <input type="checkbox" value="true" name="downstream" checked autocomplete="off">
                Downstream
              </label>
              <label class="btn active">
                <input type="checkbox" value="true" name="recursive" checked autocomplete="off">
                 Recursive
              </label>
              <label class="btn"
                title="Only consider failed task instances when clearing this one">
                <input type="checkbox" value="true" name="only_failed" autocomplete="off">
                Failed
              </label>
            </span>
            <hr/>
            <button id="btn_failed" type="button" class="btn btn-primary"
                data-action="{{ url_for('airflow.failed') }}">
              Mark Failed
            </button>
            <span class="btn-group" data-toggle="buttons">
              <label class="btn">
                <input type="checkbox" value="true" name="failed_past" autocomplete="off">
                Past
              </label>
              <label class="btn">
                <input type="checkbox" value="true" name="failed_future" autocomplete="off">
                Future
              </label>
              <label class="btn">
                <input type="checkbox" value="true" name="failed_upstream" autocomplete="off">
                Upstream
              </label>
              <label class="btn">
                <input type="checkbox" value="true" name="failed_downstream" autocomplete="off">
                Downstream
              </label>
            </span>
            <hr/>
            <button id="btn_success" type="button" class="btn btn-primary"
                data-action="{{ url_for('airflow.success') }}">
              Mark Success
            </button>
            <span class="btn-group" data-toggle="buttons">
              <label class="btn">
                <input type="checkbox" value="true" name="success_past" autocomplete="off">
                Past
              </label>
              <label class="btn">
                <input type="checkbox" value="true" name="success_future" autocomplete="off">
                Future
              </label>
              <label class="btn">
                <input type="checkbox" value="true" name="success_upstream" autocomplete="off">
                Upstream
              </label>
              <label class="btn">
                <input type="checkbox" value="true" name="success_downstream" autocomplete="off">
                Downstream
              </label>
            </span>
          </form>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">
            Close
          </button>
        </div>
      </div>
    </div>
  </div>
  <!-- Modal for dag -->
  <div class="modal fade" id="dagModal"
        tabindex="-1" role="dialog"
      aria-labelledby="dagModalLabel" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h4 class="modal-title" id="dagModalLabel">
            <span id='dag_id'></span>
          </h4>
        </div>
        <div class="modal-body">
          <form method="POST">
            <button id="btn_edit_dagrun" type="button" class="btn btn-primary">
              Edit
            </button>
            <input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/>
            <input name="dag_id" type="hidden">
            <input name="execution_date" type="hidden">
            <input name="origin" type="hidden" value="{{ request.base_url }}">
            <button id="btn_dagrun_clear" type="button" class="btn btn-primary" data-action="{{ url_for('airflow.dagrun_clear') }}">
              Clear
            </button>
            <button id="btn_dagrun_failed" type="button" class="btn btn-primary" data-action="{{ url_for('airflow.dagrun_failed') }}">
              Mark Failed
            </button>
            <button id="btn_dagrun_success" type="button" class="btn btn-primary" data-action="{{ url_for('airflow.dagrun_success') }}">
              Mark Success
            </button>
          </form>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">
            Close
          </button>
        </div>
      </div>
    </div>
  </div>
{% endblock %}
{% block tail %}
  {{ lib.form_js() }}
  {{ super() }}
  <script src="{{ url_for('static', filename='bootstrap-toggle.min.js') }}"></script>
  <script>
function updateQueryStringParameter(uri, key, value) {
  var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
  var separator = uri.indexOf('?') !== -1 ? "&" : "?";
  if (uri.match(re)) {
    return uri.replace(re, '$1' + key + "=" + value + '$2');
  }
  else {
    return uri + separator + key + "=" + value;
  }
}

    // Pills highlighting
    $(document).ready(function () {
      $('a[href*="' + this.location.pathname + '"]').parent().addClass('active');
      $('.never_active').removeClass('active');
    });

    var id = '';
    var dag_id = '{{ dag.dag_id }}';
    var task_id = '';
    var execution_date = '';
    var subdag_id = '';
    var show_es_logs = false;
    {% if show_external_logs is defined %}
      show_es_logs = '{{ show_external_logs }}' == "True";
    {% endif %}

    function call_modal(t, d, try_numbers, sd) {
      task_id = t;
      loc = String(window.location);
      $("#btn_filter").on("click", function(){
        window.location = updateQueryStringParameter(loc, "root", task_id);
      });
      subdag_id = sd;
      execution_date = d;
      $('#task_id').html(t);
      $('#execution_date').html(d);
      $('#myModal').modal({});
      $("#myModal").css("margin-top","0px")
      if (subdag_id === undefined)
          $("#div_btn_subdag").hide();
      else {
          $("#div_btn_subdag").show();
          subdag_id = "{{ dag.dag_id }}."+t;
      }

      $("#dag_dl_logs").hide();
      $("#dag_es_logs").hide();
      if (try_numbers > 0) {
          $("#dag_dl_logs").show();
          if (show_es_logs) {
              $("#dag_es_logs").show();
          }
      }

      $("#try_index > li").remove();
      $("#es_try_index > li").remove();
      var startIndex = (try_numbers > 2 ? 0 : 1);
      for (var index = startIndex; index <  try_numbers; index++) {
        var url = "{{ url_for('airflow.get_logs_with_metadata') }}" +
          "?dag_id=" + encodeURIComponent(dag_id) +
          "&task_id=" + encodeURIComponent(task_id) +
          "&execution_date=" + encodeURIComponent(execution_date) +
          "&metadata=null" +
          "&format=file";

        var showLabel = index;
        if (index != 0) {
          url += "&try_number=" + index;
        } else {
          showLabel = 'All';
        }

        $("#try_index").append(`<li role="presentation" style="display:inline">
          <a href="${url}"> ${showLabel} </a>
          </li>`
        );

        if (index == 0 || !show_es_logs) continue;
        var es_url = "{{ url_for('airflow.elasticsearch') }}" +
          "?dag_id=" + encodeURIComponent(dag_id) +
          "&task_id=" + encodeURIComponent(task_id) +
          "&execution_date=" + encodeURIComponent(execution_date) +
          "&try_number=" + index;
        $("#es_try_index").append(`<li role="presentation" style="display:inline">
          <a href="${es_url}"> ${showLabel} </a>
          </li>`
        );
      }
    }

    function call_modal_dag(dag) {
      id = dag && dag.id;
      execution_date = dag && dag.execution_date;
      $('#dag_id').html(dag_id);
      $('#dagModal').modal({});
      $("#dagModal").css("margin-top","0px");
    }


    function confirmTriggerDag(link, dag_id){
      if (confirm("Are you sure you want to run '"+dag_id+"' now?")) {
        postAsForm(link.href, {});
      }
      // Never follow the link
      return false;
    }

    function confirmDeleteDag(link, dag_id){
      if (confirm("Are you sure you want to delete '"+dag_id+"' now?\n\
        This option will delete ALL metadata, DAG runs, etc.\n\
        EXCEPT Log.\n\
        This cannot be undone.")) {
        postAsForm(link.href, {});
      }
      return false;
    }

    $("#btn_rendered").click(function(){
      url = "{{ url_for('airflow.rendered') }}" +
        "?task_id=" + encodeURIComponent(task_id) +
        "&dag_id=" + encodeURIComponent(dag_id) +
        "&execution_date=" + encodeURIComponent(execution_date);
      window.location = url;
    });

    $("#btn_subdag").click(function(){
      url = "{{ url_for( 'airflow.' + dag.get_default_view() ) }}" +
        "?dag_id=" + encodeURIComponent(subdag_id) +
        "&execution_date=" + encodeURIComponent(execution_date);
      window.location = url;
    });

    $("#btn_log").click(function(){
      url = "{{ url_for('airflow.log') }}" +
        "?task_id=" + encodeURIComponent(task_id) +
        "&dag_id=" + encodeURIComponent(dag_id) +
        "&execution_date=" + encodeURIComponent(execution_date) +
        "&format=json";
      window.location = url;
    });

    $("#btn_task").click(function(){
      url = "{{ url_for('airflow.task') }}" +
        "?task_id=" + encodeURIComponent(task_id) +
        "&dag_id=" + encodeURIComponent(dag_id) +
        "&execution_date=" + encodeURIComponent(execution_date);
      window.location = url;
    });

    $("#btn_ti").click(function(){
      url = "{{ url_for('taskinstance.index_view') }}" +
        "?flt1_dag_id_equals=" + encodeURIComponent(dag_id) +
        "&flt2_task_id_equals=" + encodeURIComponent(task_id) +
        "&sort=3&desc=1";
      window.location = url;
    });

    $('form button[data-action]').click(function (e) {
      var form = $(this).closest('form').get(0);
      form.dag_id.value = dag_id;
      form.execution_date.value = execution_date;
      form.origin.value = window.location;
      if (form.task_id) {
        form.task_id.value = task_id;
      }
      form.action = $(this).data("action");
      form.submit();
    })

    $("#pause_resume").change(function() {
      var dag_id =  $(this).attr('dag_id');
      if ($(this).prop('checked')) {
        is_paused = 'true'
      } else {
        is_paused = 'false'
      }
      url = "{{ url_for('airflow.paused') }}" + '?is_paused=' + is_paused + '&dag_id=' + encodeURIComponent(dag_id);
      $.post(url);
    });

    $('#btn_edit_dagrun').click(function(){
      window.location = "{{ url_for('dagrun.edit_view') }}?id=" + encodeURIComponent(id);
    });

  </script>
{% endblock %}
