{% extends "base.html" %}
{% block comments %}
<!--
# Copyright (c) 2014 Riverbed Technology, Inc.
#
# This software is licensed under the terms and conditions of the MIT License
# accompanying the software ("License").  This software is distributed "AS IS"
# as set forth in the License.
-->
{% endblock %}

{% load tz %}
{% load url from future %}

{% block header %}
    <link href="{{ STATIC_URL }}css/report.css" rel="stylesheet"/>
    <script type="text/javascript" src="{{ STATIC_URL }}showLoading/js/jquery.showLoading.js"></script>
    <script type="text/javascript" src="{{ STATIC_URL }}jquery-timepicker/jquery.timepicker.min.js"></script>
    <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery.form/3.32/jquery.form.js"></script>

    {% if maps_version == 'DEVELOPER' %}
        <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
    {% elif maps_version == 'FREE' %}
        <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3%key={{ maps_api_key }}&sensor=false"></script>
    {% elif maps_version == 'BUSINESS' %}
        <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3&client={{ maps_api_key }}&sensor=false"></script>
    {% endif %}

    <script type="text/javascript" src="{{ STATIC_URL }}js/rvbd-widgets.js"></script>
    <script type="text/javascript" src="{{ STATIC_URL }}js/rvbd-yui3.js"></script>

    {% if maps_version == 'OPEN_STREET_MAPS' %}
        <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.2/leaflet.js"></script>
        <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.2/leaflet.css" />
        <script type="text/javascript" src="{{ STATIC_URL }}js/rvbd-openstreetmaps.js"></script>
    {% else %}
        <script type="text/javascript" src="{{ STATIC_URL }}js/rvbd-google-maps.js"></script>
    {% endif %}


    <script type="text/javascript">
      var runRequested = false;
      var debugFlag = false;
      $(document).ready( function() {
          $.ajaxSetup({
              beforeSend: function(xhr) {
                  xhr.setRequestHeader('X-CSRFToken', '{{ csrf_token }}');
              }
          });

          {% if report.hide_criteria %}

          renderPage();
          {% if report.reload_minutes > 0 %}setInterval(renderPage, {{ report.reload_minutes }} * 60 * 1000);{% endif %}

          {% else %}

          $("#criteria").on('hidden', function() { dorun(); });
          $('form#criteriaform').submit(function() {
              run();
              return false;
          });

          {% endif %}

        });

    </script>

    <script type="text/javascript">
      var global = this;
      var rvbd_status = {};
      var rvbd_debug = false;

      // used for auto-run
      function renderPage() {
          $.ajax({
              dataType:"json",
              type: "get",
              url: "{% url 'report-widgets' report.namespace report.slug %}",
              success: function(data, textStatus, jqXHR) {
                  renderReport(data);
              },
              error: function(jqXHR, textStatus, errorThrown) {
                  // we receive a 400 error on form validation problems
                  if (jqXHR.status == 400) {
                      alert("an error occurred: " + textStatus + " : " + errorThrown);
                  }
                  if (jqXHR.status == 500) {
                      alert("an error occurred: " + textStatus + " : " + errorThrown);
                  }
              }
          });
      }

      function renderReport(widgets) {
          // reset the status
          global.rvbd_status = {};

          // pull first element off list which contains information about the report
          var report_meta = widgets.shift();
          $('#report_datetime').html(report_meta.datetime);
          $('#report_timezone').html(report_meta.timezone);
          rvbd_debug = report_meta.debug;

          var report=$("#report");
          report.html(widgets);
          var rownum=0;
          var row;
          $.each(widgets, function(i,w) {
              if (rownum != w.row) {
                  row = $('<div />', { 'class': 'row-fluid' }).appendTo(report); 
                  rownum = w.row;
              }
              var wid = "chart_" + w.widgetid;
              $('<div />',
                { id: wid,
                  'class': 'blackbox span' + w.width })
                  .text ("Widget " + w.widgetid)
                  .appendTo(row);

              var opts = w.options || {};
              opts.height = w.height;
              new global[w.widgettype[0]][w.widgettype[1]] ( w.posturl, wid, opts, w.criteria );
              rvbd_status[w.posturl] = 'running';
          });

          // wait a short period before checking widget status
          setTimeout(monitorWidgetStatus, 100);
      }

      function monitorWidgetStatus() {
          // keep checking while at least one widget is running
          for (var key in global.rvbd_status) {
              if (global.rvbd_status[key] == 'running') {
                  setTimeout(monitorWidgetStatus, 500);
                  return;
              };
          };
          // all statuses are not 'running', trigger the zipfile download
          if (global.rvbd_debug == true) {
              alert('Complete - you will now be prompted to download a zipfile ' +
                    'containing the server logs.');
              window.location = "{% url 'steelscript.appfwk.apps.report.views.download_debug' %}";
          };
      }

      function updateTimeAndRun() {
          $('#timenow').click();
          run();
      }

      function run() {
          runRequested = true;
          $("#criteria").collapse('hide');
      }

      function runDebug() {
          debugFlag = true;
          run();
      }

      function dorun() {
          if (!runRequested)
              return;
          runRequested = false;
          $("#id_debug").val(debugFlag ? "on" : "");
          $("#form-error-info").html("");
          form = $('form#criteriaform');
          $("body").css("cursor", "wait");
          form.ajaxSubmit({
              dataType:"json",
              type: "post",
              url: form.attr('action'),
              success: function(data, textStatus) { 
                  $("body").css("cursor", "default");
                  renderReport(data);
              },
              error: function(jqXHR, textStatus, errorThrown) { 
                  // we receive a 400 error on form validation problems
                  $("body").css("cursor", "default");
                  if (jqXHR.status == 400) {
                      $("#criteria").collapse('show');
                      $("#form-error-info").html(jqXHR.responseText);
                  }
                  if (jqXHR.status == 500) {
                      alert("an error occurred: " + textStatus + " : " + errorThrown);
                  }
              }
          });
          debugFlag = false;
      }

      function update_criteria(data) {
          $.each(data, function(i,w) { 
              //alert('Updating ' + i + ',' + w + ' #' + w.id + '-span' + '\n' + w.html);
              $('#' + w.id + '-span').html(w.html);
          });
      }
      function criteria_changed() {
          $("body").css("cursor", "wait");
          form = $('form#criteriaform');
          form.ajaxSubmit({
              dataType:"json",
              type: "post",
              url: form.attr('action') + 'criteria/',
              success: function(data, textStatus) { 
                  $("body").css("cursor", "default");
                  update_criteria(data);
              },
              error: function(jqXHR, textStatus, errorThrown) { 
                  $("body").css("cursor", "default");
                  alert("Failed: jqXHR: " + jqXHR.status + "\ntextStatus: " + textStatus);

                  // we receive a 400 error on form validation problems
                  if (jqXHR.status == 400) {
                      $("#criteria").collapse('show');
                      $("#form-error-info").html(jqXHR.responseText);
                  }
                  if (jqXHR.status == 500) {
                      alert("an error occurred: " + textStatus + " : " + errorThrown);
                  }
              }
          });
      }

    </script>
    <style>
        .loading-indicator
        {
            height: 80px;
            width: 80px;
            background: url( '{{ STATIC_URL }}showLoading/images/loading.gif' );
            background-repeat: no-repeat;
            background-position: center center;
        }
    </style>
{% endblock %}

{% block header_row %}<h3>{{ report.title }}</h3>{% endblock %}

{% block content %}
    {% if not report.hide_criteria %}
    <div class="container-fluid">
      <div class="row-fluid">
        <div class="span12 widget-box">
          <div class="widget-title">
            <a data-toggle="collapse" data-target="#criteria" href="#">
              Criteria
            </a>
          </div>
          <div class="collapse in" id="criteria">
            <div class="widget-content">
                <form class="form-horizontal" action="{% url 'report-view' report.namespace report.slug %}" method="post" id="criteriaform"
                        {% if form.is_multipart %}enctype="multipart/form-data"{% endif %}>
                    {% csrf_token %}
                    <fieldset>
                        <div id="form-error-info" class="text-error"></div>

                        {% if form.errors %}
                            <p class="text-error">Please correct the errors below.</p>
                        {% endif %}

                        {% for s in section_map %}
                            <div class="criteria-group">
                                {% if show_sections %}
                                    <div class="criteria-group-title"> {{ s.title }} </div>
                                {% endif %}
                                <div class="criteria-group-contents">
                                    {% for field in form.visible_fields %}
                                        {% if field.name in s.parameters %}
                                        <div class="control-group">
                                            <div class="control-label">
                                                {{ field.label_tag }} 
                                            </div>
                                            <div class="controls">
                                                <span id='{{ field.auto_id }}-span'>{{ field }}</span>
                                                {% if field.errors %}
                                                    {% for err in field.errors %}
                                                        <p class="text-error">{{ err }}</p>
                                                    {% endfor %}
                                                {% endif %}
                                                {% if field.help_text %} 
                                                    <span class="icon-info-sign" title="{{ field.help_text }}"></span>
                                                {% endif %}
                                            </div>
                                        </div>
                                        {% endif %}
                                    {% endfor %}
                                </div>
                            </div>
                        {% endfor %}
                        {% for hidden in form.hidden_fields %}
                            {{ hidden }}
                        {% endfor %}
                    </fieldset>
              </form>
              <p></p>
              <div class="btn-group dropup">
                  <button class="btn btn-primary" onclick="run()">Run</button>
                  <button class="btn btn-primary dropdown-toggle" data-toggle="dropdown">
                    <span class="caret"></span>
                  </button>
                  <ul class="dropdown-menu">
                      {% if developer %}
                          <li><a href="#" onclick="runDebug()"> Debug This Report </a></li>
                      {% endif %}
                      <li><a href="#" onclick="updateTimeAndRun()"> Update Time & Run </a></li>
                      <li class="divider"></li>
                      <li><a href="#" onclick="run()"> Run Report </a></li>
                  </ul>
              </div>
            </div>
          </div> 
        </div> 
      </div> 
    </div>
    {% endif %}
  
    <div class="container-fluid">
      <div class="row-fluid">
        <div class="span12 widget-box">
          <div class="widget-title">
            <a data-toggle="collapse" data-target="#report-container" href="#">
              {% if report.hide_criteria %}
                {{ report.title }}
                <small id="report_datetime" class="text-info pull-right">{% now "jS F Y H:i:s" %}</small><br>
              {% else %}
                Report
              {% endif %}
            </a>
          </div>
          <div class="collapse in" id="report-container">
            <div class="widget-content collapse in" id="report">
            </div> <!-- criteria -->
          </div> <!-- criteria -->
        </div> <!-- span12 -->
      </div> <!-- row-fluid -->
    </div>

{% endblock %}
