{% extends '_layout.html' %}

{% block script %}
  var ws_scheme = 'ws';
  if (window.location.protocol == 'https:'){
    ws_scheme = 'wss';
  }
  var ws = new WebSocket(ws_scheme + "://" + window.location.host + "/websocket");

  if (Notification.permission !== "denied") {
    Notification.requestPermission();
  }

  ws.onmessage = function(evt) {
    console.log(evt.data);
    var data = JSON.parse(evt.data);

    for (uuid in data) {
      var element = document.getElementById(uuid);
      element.className = element.className.replace(/status\-[a-z]*/g, "status-" + data[uuid]["status"]);
      if (data[uuid]["status"].match("error|critical")) {
        var notification = new Notification(
          "The service " + data[uuid]["service"] + " on " + data[uuid]["server"] + " is " + data[uuid]["status"],
          {"body": data[uuid]["message"]});
      }
    }
  };

  ws.onclose = function(evt){
    var notification = new Notification("Watchghost disconnected from server");
    var headers = document.getElementsByTagName('header');
    for (var i = 0; i < headers.length; i++) {
      headers[i].innerHTML = headers[i].innerHTML + ' (disconnected)';
    }
    document.title = document.title + '(disconnected)';
    var articles = document.getElementsByTagName('article');
    for (var i = 0; i < articles.length; i++) {
      var article = articles[i];
      var list_items = article.getElementsByTagName('li');
      for(var j = 0; j < list_items.length; j++){
        var list_item = list_items[j];
        list_item.className = list_item.className.replace(/status\-[a-z]*/g, "status-unknown");
      }
    }
  }
{% end %}

{% block main %}
  {% for server_name, server in servers.items() %}
    <article id="{{ server.uuid }}">
      <h2>{{ server.name }}</h2>
      <ul>
        {% for watcher in server.watchers %}
          <li id="{{ watcher.uuid }}" class="module-{{ watcher.service.name.split('.')[0].lower() }} status-{{ watcher.status or 'unknown' }}">
            <a href="{{ reverse_url('Watcher', watcher.uuid) }}">
              {% if watcher.description %}
                {{ watcher.description }}
              {% else %}
                {{ watcher.service.name.split('.')[-1].lower() }}
              {% end %}
            </a>
          </li>
        {% end %}
      </ul>
    </article>
  {% end %}
{% end %}
