{% extends 'base.html' %}

{% block content %}
<div class="row">
  <div class="col-xs-12">
    <div class="col-xs-10 col-xs-offset-2">
      <h2>{% if form.instance.id %}Edit check{% else %}New check{% endif %}</h2>
    </div>
  </div>
</div>
<form class="form-horizontal" action="" method="post" role="form">
  {% include "cabotapp/_base_form.html" %}
  <div class="col-xs-12">
    <div class="form-group">
      <div class="col-xs-6 col-xs-offset-2">
        <button type="submit" class="btn btn-primary">Submit</button>
        <a href="{% url "dashboard" %}" class="btn">Back to dashboard</a>
      </div>
      {% if form.instance.id %}
      <div class="col-xs-4">
        <a class="btn btn-danger" href="{% url "delete-check" form.instance.id %}">Delete check</a>
      </div>
      {% endif %}
      </div>
    </div>
  </div>
</form>
{% endblock %}

{% load compress %}
{% block js %}
{{ block.super }}
{% compress js %}
<script type="text/coffeescript">
GRAPHITE_ENDPOINT = '/graphite/'

$(document).ready ->
  updateGraphiteData()
  $('#id_metric').on('keyup', complete)
  $('#id_frequency').on('keyup', complete)

  complete = () ->
      clearTimeout(timer)
      timer = setTimeout(updateGraphiteData, 1000)

  $('#id_metric').autocomplete
    source: (request, response) ->
      $.ajax
        url: GRAPHITE_ENDPOINT
        data:
          metric: request.term
      .done (data) ->
        metricList = data.matchingMetrics?.metrics?.metrics
        if metricList
          metrics = (m.path for m in metricList)
          response metrics
    minLength: 0
    close: (evt, ui) ->
      if $('#id_metric').is(':focus')
        $('#id_metric').autocomplete("search", $('#id_metric').val())

previousTerm = undefined

updateGraphiteData = () ->
  m = $('#id_metric').val()
  f = $('#id_frequency').val()
  if !m or previousTerm == m
    return
  previousTerm = m
  $('#graphite_data_container').text 'Getting data'
  $.ajax
    url: GRAPHITE_ENDPOINT
    data:
      metric: m
      frequency: f
  .done (data) ->
    if data.data? and data.data.length? != 0
      $('#graphite_data_container').text JSON.stringify(data.data, undefined, 2)
      drawMorris data.data
    else
      $('#graphite_data_container').text 'Select a valid metric'
      removeMorris()

drawMorris = (data) ->
  kvs = []
  labels = []
  $('#graph').show()
  all = {}
  for series in data
    label = series.target
    labels.push label
    for point in series.datapoints
      t = point[1]*1000
      if not all[t]?
        all[t] = {}
      all[t][label] = point[0]
  for k, v of all
    tmp = {time: parseInt(k)}
    for k2, v2 of v
      tmp[k2] = v2
    kvs.push tmp

  $('#graph').empty()
  if not kvs
    return
  window.morrisLine = Morris.Line
    element: 'graph'
    data: kvs
    xkey: 'time'
    ykeys: labels
    labels: (label[0..10] + '...' + label[-10..] for label in labels)
    hideHover: 'auto'

removeMorris = () ->
  $('#graph').hide()

</script>
{% endcompress %}
{% endblock %}
