{% extends "tesm_core/base.html" %}
{% from "tesm_core/macros.html" import field, select_field, textarea_field, checkbox, pill,
        search_box, modal, empty_state, alert %}

{# Neustart-Bedienelement.

   Ein einziger moeglicher Weg: ein Knopf, der ihn benennt. Mehrere: ein Knopf
   fuer den bevorzugten Weg (PoE, weil er auch bei haengendem Betriebssystem
   wirkt) und daneben die Auswahl. Kein Weg: gar nichts -- ein Knopf, der
   verlaesslich nichts bewirkt, ist schlimmer als kein Knopf. #}
{% macro restart_control(device, methods, compact=False) %}
  {% if methods %}
    {% set first = methods[0] %}
    <form method="post" class="row row--tight" style="display:inline-flex"
          action="{{ url_for('devices.restart_device', device_id=device.id) }}" data-no-guard>
      <input type="hidden" name="{{ csrf_field_name }}" value="{{ csrf_token() }}">
      <input type="hidden" name="method" value="{{ first.key }}">
      <button class="btn btn--sm{{ ' btn--ghost' if compact else '' }}" type="submit"
              title="{{ first.hint }}" data-busy-label="Startet ..."
              data-confirm="{{ device.name }} ueber {{ first.label }} neu starten? {{ first.hint }}"
              data-confirm-title="Neustart" data-confirm-ok="Neu starten"
              data-confirm-style="primary">
        {{ icon('power', size=15) }}{% if not compact %} {{ first.label }}{% endif %}
      </button>
    </form>
    {% if methods | length > 1 %}
      {% for other in methods[1:] %}
        <form method="post" style="display:inline"
              action="{{ url_for('devices.restart_device', device_id=device.id) }}" data-no-guard>
          <input type="hidden" name="{{ csrf_field_name }}" value="{{ csrf_token() }}">
          <input type="hidden" name="method" value="{{ other.key }}">
          <button class="btn btn--sm btn--ghost" type="submit" title="{{ other.hint }}"
                  data-busy-label="Startet ..."
                  data-confirm="{{ device.name }} ueber {{ other.label }} neu starten? {{ other.hint }}"
                  data-confirm-title="Neustart" data-confirm-ok="Neu starten"
                  data-confirm-style="primary">
            {{ other.label }}
          </button>
        </form>
      {% endfor %}
    {% endif %}
  {% endif %}
{% endmacro %}

{% macro device_form(device=None, scope='neu') %}
  <div class="form-grid">
    {{ field('name', 'Name', value=device.name if device else '', required=True) }}
    {{ field('mac', 'MAC-Adresse', value=device.mac if device else '', required=True,
             placeholder='aa:bb:cc:dd:ee:ff', extra_class='') }}
    {{ field('ip', 'IP-Adresse', value=device.ip if device else '', required=True,
             placeholder='192.168.1.50') }}
    <label class="field">
      <span class="field__label">Switch</span>
      <select class="select" name="switch_id">
        <option value="">kein Switch</option>
        {% for switch in switches %}
          <option value="{{ switch.id }}"
            {% if device and device.switch_id == switch.id %}selected{% endif %}>
            {{ switch.hostname }} ({{ switch.ip }})
          </option>
        {% endfor %}
      </select>
    </label>
    {{ field('port', 'Port am Switch', value=device.port if device else '',
             placeholder='1 oder 1/1/3',
             hint_text='Pflicht, sobald ein Switch zugeordnet ist.') }}
    <label class="field">
      <span class="field__label">Zugangsdaten (fuer Wartung)</span>
      <select class="select" name="credential_id" data-behavior="toggle-target"
              data-toggle-value="__neu__" data-toggle-target="#new-credential-{{ scope }}">
        <option value="">keine</option>
        {% for credential in credentials %}
          <option value="{{ credential.id }}"
            {% if device and device.credential_id == credential.id %}selected{% endif %}>
            {{ credential.name }} ({{ category_labels.get(credential.category, credential.category) }})
          </option>
        {% endfor %}
        {% if current_user.has('credentials.create') %}
          <option value="__neu__">-- neue Zugangsdaten anlegen --</option>
        {% endif %}
      </select>
    </label>
    {% if current_user.has('credentials.create') %}
      <fieldset class="field field--full" id="new-credential-{{ scope }}" hidden>
        <legend class="field__label">Neue Zugangsdaten</legend>
        <div class="form-grid">
          {{ field('new_credential_name', 'Bezeichnung', placeholder='z. B. Wartung Linux',
                   hint_text='Der Eintrag wird zusaetzlich unter Zugangsdaten gespeichert und
                              ist danach fuer weitere Geraete verwendbar.') }}
          {{ field('new_credential_username', 'Benutzer') }}
          {{ field('new_credential_secret', 'Passwort', type='password') }}
          <label class="field">
            <span class="field__label">Kategorie</span>
            <select class="select" name="new_credential_category">
              {% for value, label in credential_categories %}
                <option value="{{ value }}" {% if value == 'linux' %}selected{% endif %}>{{ label }}</option>
              {% endfor %}
            </select>
            <span class="field__hint" id="category-effect-{{ scope }}"></span>
          </label>
        </div>
      </fieldset>
    {% endif %}
    {{ field('ssh_port', 'SSH-Port des Geraets', value=device.ssh_port if device else 22, type='number') }}
    <label class="field">
      <span class="field__label">Kategorie</span>
      <select class="select" name="category">
        {% for value, label in categories %}
          <option value="{{ value }}" {% if device and device.category == value %}selected{% endif %}>{{ label }}</option>
        {% endfor %}
      </select>
    </label>
    {{ field('location', 'Standort', value=device.location if device else '') }}
    {{ textarea_field('notes', 'Notizen', value=device.notes if device else '', rows=2,
                      extra_class='field--full') }}
  </div>
  <div class="stack stack--tight">
    {{ checkbox('is_active', 'Geraet wird ueberwacht', checked=device.is_active if device else True) }}
    {{ checkbox('auto_restart', 'Automatischer PoE-Neustart bei Ausfall',
                checked=device.auto_restart if device else True,
                hint_text='Greift nur mit gueltiger Lizenz und zugeordnetem Switch-Port.') }}
  </div>
{% endmacro %}

{% block page_title %}Clients{% endblock %}
{% block page_sub %}
  {{ devices | length }} Geraete &middot; {{ counts.online }} erreichbar, {{ counts.offline }} nicht erreichbar
{% endblock %}

{% block topbar_extra %}
  {{ search_box('devices-table', 'Name, IP, MAC, Switch ...', count_id='devices-visible') }}
  {% if current_user.has('devices.create') %}
    <button class="btn btn--primary btn--sm" type="button" data-dialog-open="device-new">
      {{ icon('plus', size=15) }} Geraet anlegen
    </button>
  {% endif %}
{% endblock %}

{% block content %}
<section class="card">
  <div class="table-toolbar">
    <span class="muted fs-sm"><span id="devices-visible">{{ devices | length }}</span> sichtbar</span>
    <span class="table-toolbar__spacer"></span>
    <a class="btn btn--sm btn--ghost" href="{{ url_for('tesmlogs.restarts') }}">
      {{ icon('power', size=15) }} Neustarts
    </a>
  </div>
  <div class="table-wrap">
    <table class="table" id="devices-table" data-behavior="sortable">
      <thead>
        <tr>
          <th class="sortable">Name</th>
          <th class="sortable">Zustand</th>
          <th class="sortable">IP</th>
          <th class="sortable">MAC</th>
          <th class="sortable">Zugangsdaten</th>
          <th class="sortable">Switch / Port</th>
          <th class="sortable">Letzte Pruefung</th>
          <th class="sortable">Host-Schluessel</th>
          <th class="actions">Aktion</th>
        </tr>
      </thead>
      <tbody>
        {% for device in devices %}
          <tr data-filter-text="{{ device.name }} {{ device.ip }} {{ device.mac }} {{ device.switch_hostname or '' }} {{ device.location }} {{ device.category }}">
            <td>
              <a class="fw-600" href="{{ url_for('devices.detail', device_id=device.id) }}">{{ device.name }}</a>
              {% if not device.is_active %}{{ pill('deaktiviert', '') }}{% endif %}
              {% if not device.auto_restart %}
                <span class="hint-icon" title="Automatischer PoE-Neustart ist fuer dieses Geraet abgeschaltet">!</span>
              {% endif %}
              {% if device.location %}<div class="fs-xs faint">{{ device.location }}</div>{% endif %}
            </td>
            <td data-sort-value="{{ device.state }}">
              {% if not device.is_active %}{{ pill('aus', '') }}
              {% elif device.state == 'online' %}{{ pill('online', 'online') }}
              {% elif device.state == 'offline' %}{{ pill('offline', 'offline') }}
              {% else %}{{ pill('unbekannt', 'warning') }}{% endif %}
              {% if device.fail_count %}<span class="fs-xs faint">({{ device.fail_count }}&times;)</span>{% endif %}
            </td>
            <td class="mono fs-sm">{{ device.ip }}</td>
            <td class="mono fs-sm">{{ device.mac }}</td>
            <td class="fs-sm">
              {% if device.credential_name %}
                {{ device.credential_name }}
                <div class="fs-xs faint">
                  {{ category_labels.get(device.credential_category, device.credential_category) }}
                </div>
              {% else %}<span class="faint">keine</span>{% endif %}
            </td>
            <td class="fs-sm">
              {% if device.switch_hostname %}
                {{ device.switch_hostname }} <span class="faint">/</span> {{ device.port }}
              {% else %}<span class="faint">nicht zugeordnet</span>{% endif %}
            </td>
            <td class="fs-sm" data-sort-value="{{ device.last_check_at or '' }}">
              {% if device.last_check_at %}
                <span data-relative-time="{{ device.last_check_at }}">{{ device.last_check_at | dt }}</span>
              {% else %}<span class="faint">nie</span>{% endif %}
            </td>
            <td data-sort-value="{{ '1' if device.host_key_known else '0' }}">
              {% if device.credential_category == 'windows' %}
                <span class="faint fs-xs" title="Windows wird nicht ueber SSH verwaltet">
                  nicht noetig
                </span>
              {% elif device.host_key_known %}{{ pill('freigegeben', 'online') }}
              {% else %}
                <a href="{{ url_for('hostkeys.overview') }}"
                   title="Ohne Freigabe verweigern Wartung und Konsole die Verbindung">
                  {{ pill('offen', 'warning') }}
                </a>
              {% endif %}
            </td>
            <td class="actions">
              {% if current_user.has('devices.execute') %}
                {{ restart_control(device, restart_methods.get(device.id, []), compact=True) }}
              {% endif %}
              {% if current_user.has('devices.edit') %}
                <button class="btn btn--sm btn--ghost" type="button"
                        data-dialog-open="device-edit-{{ device.id }}" aria-label="Bearbeiten">
                  {{ icon('pencil', size=15) }}
                </button>
              {% endif %}
              {% if current_user.has('devices.delete') %}
                <form method="post" action="{{ url_for('devices.delete', device_id=device.id) }}"
                      style="display:inline" data-no-guard>
                  <input type="hidden" name="{{ csrf_field_name }}" value="{{ csrf_token() }}">
                  <button class="btn btn--sm btn--ghost danger-text" type="submit" aria-label="Loeschen"
                          data-confirm="{{ device.name }} in den Papierkorb verschieben? Die MAC bleibt dabei reserviert."
                          data-confirm-title="Geraet loeschen" data-confirm-ok="Loeschen">
                    {{ icon('trash', size=15) }}</button>
                </form>
              {% endif %}
            </td>
          </tr>
        {% endfor %}
      </tbody>
    </table>
  </div>
  {% if not devices %}
    {{ empty_state('Keine Geraete', 'Legen Sie das erste ueberwachte Geraet an.', 'cpu') }}
  {% endif %}
</section>

{{ alert('Ein PoE-Neustart setzt Switch und Port voraus, ein Neustart ueber SSH oder
RPC setzt passende Zugangsdaten voraus. Ist keine Methode moeglich, erscheint der Knopf
nicht -- damit kein Neustart vorgetaeuscht wird, der nichts bewirkt.', 'info') }}
{% endblock %}


{% block dialogs %}
{% if current_user.has('devices.create') %}
  {% call modal('device-new', 'Geraet anlegen', 'MAC und IP sind Pflicht', 'wide') %}
    <form method="post" action="{{ url_for('devices.create') }}">
      <input type="hidden" name="{{ csrf_field_name }}" value="{{ csrf_token() }}">
      <div class="modal__body">{{ device_form(scope='neu') }}</div>
      <div class="modal__footer">
        <button class="btn" type="button" data-dialog-close>Abbrechen</button>
        <button class="btn btn--primary" type="submit">Anlegen</button>
      </div>
    </form>
  {% endcall %}
{% endif %}

{% if current_user.has('devices.edit') %}
  {% for device in devices %}
    {% call modal('device-edit-' ~ device.id, device.name, device.mac, 'wide') %}
      <form method="post" action="{{ url_for('devices.update', device_id=device.id) }}">
        <input type="hidden" name="{{ csrf_field_name }}" value="{{ csrf_token() }}">
        <div class="modal__body">{{ device_form(device, scope=device.id) }}</div>
        <div class="modal__footer">
          <button class="btn" type="button" data-dialog-close>Abbrechen</button>
          <button class="btn btn--primary" type="submit">Speichern</button>
        </div>
      </form>
    {% endcall %}
  {% endfor %}
{% endif %}
{% endblock %}
