{% extends "panoramix/base.html" %}
{% block head_css %}
{{super()}}
<style>
.select2-container-multi .select2-choices {
  height: 70px; 
  overflow: auto;
}
.no-gutter > [class*='col-'] {
    padding-right:0;
    padding-left:0;
}
form div.form-control {
  margin-bottom: 5px !important;
}
form input.form-control {
  margin-bottom: 5px !important;
}
.tooltip-inner {
  max-width: 350px;
  //width: 350px; 
}

</style>
{% endblock %}
{% block content_fluid %}
<div class="container-fluid">
  <div class="col-md-3">
    <h3>
      {{ datasource.name }}
      {% if datasource.description %}
        <i class="fa fa-info-circle" data-toggle="tooltip" data-placement="bottom" title="{{ datasource.description }}"></i>
      {% endif %}
      <a href="/{{ datasource.baselink }}/edit/{{ datasource.id }}">
        <i class="fa fa-edit"></i>
      </a>
    </h3>

    <hr>
    <form id="query" method="GET" style="display: none;">
      <div>{{ form.viz_type.label }}: {{ form.viz_type(class_="form-control select2") }}</div>
      {% if 'metrics' not in viz.hidden_fields %}
        <div>{{ form.metrics.label }}: {{ form.metrics(class_="form-control select2") }}</div>
      {% endif %}
      {% if 'granularity' not in viz.hidden_fields %}
      <div>{{ form.granularity.label }}
         <i class="fa fa-info-circle" data-toggle="tooltip" data-placement="right"
           title="Supports natural language time as in '10 seconds', '1 day' or '1 week'" 
           id="blah"></i>
        {{ form.granularity(class_="form-control select2_free_granularity") }}</div>
      {% endif  %}
      <div class="row">
        <div class="form-group">
          <div class="col-xs-6">{{ form.since.label }}
           <i class="fa fa-info-circle" data-toggle="tooltip" data-placement="right"
             title="Supports natural language time as in '1 day ago', '28 days' or '3 years'" 
             id="blah"></i>
            {{ form.since(class_="form-control select2_free_since") }}</div>
          <div class="col-xs-6">{{ form.until.label }}
            {{ form.until(class_="form-control select2_free_until") }}</div>
        </div>
      </div>
      {% if 'groupby' not in viz.hidden_fields %}
        <div>{{ form.groupby.label }}: {{ form.groupby(class_="form-control select2") }}</div>
      {% endif %}
      {% block extra_fields %}{% endblock %}
      <hr>
      <h4>Filters</h4>
        <div id="flt0" style="display: none;">
            <span class="">{{ form.flt_col_0(class_="form-control inc") }}</span>
          <div class="row">
            <span class="col col-sm-4">{{ form.flt_op_0(class_="form-control inc") }}</span>
            <span class="col col-sm-6">{{ form.flt_eq_0(class_="form-control inc") }}</span>
            <button type="button" class="btn btn-sm remove" aria-label="Delete filter">
              <span class="glyphicon glyphicon-minus"  aria-hidden="true"></span>
            </button>
          </div>
          <hr style="margin: 5px 0px;"/>
        </div>
      <div id="filters"></div>
      <button type="button" id="plus" class="btn btn-sm" aria-label="Add a filter">
        <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>
      </button>
      <hr>
      <button type="button" class="btn btn-primary" id="druidify">Druidify!</button>
      <button type="button" class="btn btn-default" id="bookmark">Bookmark</button>
      <hr style="margin-bottom: 0px;">
      <img src="{{ url_for("static", filename="tux_panoramix.png") }}" width=250>
    </form><br>
  </div>

  <div class="col-md-9">
    <h3>{{ viz.verbose_name }}
    {% if results %}
        <span class="label label-success">
            {{ "{0:0.4f}".format(results.duration.total_seconds()) }} s
        </span>
        <span class="label label-info btn" 
            data-toggle="modal" data-target="#query_modal">query</span>
    {% endif %}
    </h3>
    <hr/>
    {% block viz %}
        {% if error_msg %}
            <span class="alert alert-danger">{{ error_msg }}</span>
        {% endif %}
    {% endblock %}

    {% if debug %}
    <h3>Results</h3>
    <pre>
      {{ results }} 
    </pre>

    <h3>Latest Segment Metadata</h3>
    <pre>
               {{ latest_metadata }} 
    </pre>
    {% endif %}
  </div>
</div>
<div class="modal fade" id="query_modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="myModalLabel">Query</h4>
      </div>
      <div class="modal-body">
        <pre>{{ results.query }}</pre>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>
{% endblock %}

{% block tail_js %}
{{ super() }}
<script src="{{ url_for("static", filename="d3.min.js") }}"></script>
<script>
$( document ).ready(function() {
  f = d3.format(".4s");
  function getParam(name) {
      name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
      var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
          results = regex.exec(location.search);
      return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
  }

  $(".select2").select2();
  $("form").slideDown("slow");
  $('[data-toggle="tooltip"]').tooltip();

  function set_filters(){
    for (var i=1; i<10; i++){
      var eq = getParam("flt_eq_" + i);
      if (eq !=''){
        add_filter(i);
      }
    }
  }
  set_filters();

  function add_filter(i) {
      cp = $("#flt0").clone();
      $(cp).appendTo("#filters");  
      $(cp).slideDown("slow");
      if (i != undefined){
        $(cp).find("#flt_eq_0").val(getParam("flt_eq_" + i));
        $(cp).find("#flt_op_0").val(getParam("flt_op_" + i));
        $(cp).find("#flt_col_0").val(getParam("flt_col_" + i));
      }

      $(cp).find('select').select2();
      $(cp).find('.remove').click(function() {
        $(this).parent().parent().slideUp("slow", function(){$(this).remove()});
      });
  }
  $("#plus").click(add_filter);
  $("#bookmark").click(function () {alert("Not implemented yet...");})
  add_filter();
  $("#druidify").click(function () {
    var i = 1;

    // removing empty filters
    $("#filters > div").each(function(){
      if ($(this).find("#flt_eq_0").val() == '')
        $(this).slideUp();
    });

    // Assigning the right id to form elements in filters
    $("#filters > div").each(function(){
      $(this).attr("id", function(){return "flt_" + i;})
      $(this).find("#flt_col_0")
        .attr("id", function(){return "flt_col_" + i;})
        .attr("name", function(){return "flt_col_" + i;});
      $(this).find("#flt_op_0")
        .attr("id", function(){return "flt_op_" + i;})
        .attr("name", function(){return "flt_op_" + i;});
      $(this).find("#flt_eq_0")
        .attr("id", function(){return "flt_eq_" + i;})
        .attr("name", function(){return "flt_eq_" + i;});
      i++;
    });
    $("#query").submit();
  });

  function create_choices (term, data) { 
      if ($(data).filter(function() { 
          return this.text.localeCompare(term)===0; 
      }).length===0) 
      {return {id:term, text:term};} 
  }
  $(".select2_free_since").select2({
      createSearchChoice: create_choices,
      multiple: false,
      data: [
        {id: '-1 hour', text: '-1 hour'},
        {id: '-12 hours', text: '-12 hours'},
        {id: '-1 day', text: '-1 day'},
        {id: '-7 days', text: '-7 days'},
        {id: '-28 days', text: '-28 days'},
        {id: '-90 days', text: '-90 days'},
        {id: '{{ form.data.since }}', text: '{{ form.data.since }}'},
      ]
  });
  $(".select2_free_until").select2({
      createSearchChoice: create_choices,
      multiple: false,
      data: [
        {id: '{{ form.data.until }}', text: '{{ form.data.until }}'},
        {id: 'now', text: 'now'},
        {id: '-1 day', text: '-1 day'},
        {id: '-7 days', text: '-7 days'},
        {id: '-28 days', text: '-28 days'},
        {id: '-90 days', text: '-90 days'},
      ]
  });
  $(".select2_free_granularity").select2({
      createSearchChoice: create_choices,
      multiple: false,
      data: [
        {id: '{{ form.data.granularity }}', text: '{{ form.data.granularity }}'},
        {id: 'all', text: 'all'},
        {id: '5 seconds', text: '5 seconds'},
        {id: '30 seconds', text: '30 seconds'},
        {id: '1 minute', text: '1 minute'},
        {id: '5 minutes', text: '5 minutes'},
        {id: '1 day', text: '1 day'},
        {id: '7 days', text: '7 days'},
      ]
  });
});
</script>
{% endblock %}
