{% extends "tesm_core/base.html" %}
{% from "tesm_core/macros.html" import pill, empty_state, alert %}

{% block page_title %}{{ device.name }}{% endblock %}
{% block page_sub %}{{ device.ip }} &middot; {{ device.mac }}{% endblock %}

{% block breadcrumb %}
<nav class="breadcrumb">
  <span><a href="{{ url_for('devices.overview') }}">Clients</a></span><span>{{ device.name }}</span>
</nav>
{% endblock %}

{% block topbar_extra %}
  {% if terminal_enabled and current_user.has('maintenance.execute') and device.credential_id %}
    <a class="btn btn--sm" href="{{ url_for('terminal.device_console', device_id=device.id) }}">
      {{ icon('terminal', size=15) }} Konsole
    </a>
  {% endif %}
  {% if current_user.has('devices.execute') and restart_methods %}
    {% for method in restart_methods %}
      <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="{{ method.key }}">
        <button class="btn btn--sm {{ 'btn--primary' if loop.first else 'btn--ghost' }}"
                type="submit" title="{{ method.hint }}" data-busy-label="Startet ..."
                data-confirm="{{ device.name }} ueber {{ method.label }} neu starten? {{ method.hint }}"
                data-confirm-title="Neustart" data-confirm-ok="Neu starten"
                data-confirm-style="primary">
          {{ icon('power', size=15) }} {{ method.label }}
        </button>
      </form>
    {% endfor %}
  {% endif %}
{% endblock %}

{% block content %}
{% if device.deleted_at %}
  {{ alert('Dieses Geraet liegt im Papierkorb (geloescht am ' ~ (device.deleted_at | dt) ~ ').',
  'warning') }}
{% endif %}

<div class="grid grid--split">
  <div class="stack">
    <section class="card">
      <div class="card__header">
        <div class="flex-1">
          <div class="card__title">
            {{ icon('activity', size=17) }} Zustand
            {% if not device.is_active %}{{ pill('deaktiviert', '') }}
            {% elif device.state == 'online' %}{{ pill('online', 'online') }}
            {% elif device.state == 'offline' %}{{ pill('offline', 'offline') }}
            {% else %}{{ pill('unbekannt', 'warning') }}{% endif %}
          </div>
        </div>
      </div>
      <div class="card__body">
        <div class="grid grid--4">
          <div class="stat">
            <span class="stat__label">Antwortzeit</span>
            <span class="stat__value">{{ '%.1f' | format(device.latency_ms) if device.latency_ms else '&ndash;' | safe }}</span>
            <span class="stat__hint">Millisekunden</span>
          </div>
          <div class="stat {{ 'stat--danger' if device.fail_count else '' }}">
            <span class="stat__label">Fehlversuche</span>
            <span class="stat__value">{{ device.fail_count or 0 }}</span>
            <span class="stat__hint">in Folge</span>
          </div>
          <div class="stat">
            <span class="stat__label">Neustarts</span>
            <span class="stat__value">{{ device.restart_count or 0 }}</span>
            <span class="stat__hint">insgesamt</span>
          </div>
          <div class="stat">
            <span class="stat__label">Zuletzt erreichbar</span>
            <span class="stat__value fs-lg">
              {% if device.last_ok_at %}
                <span data-relative-time="{{ device.last_ok_at }}">{{ device.last_ok_at | dt }}</span>
              {% else %}&ndash;{% endif %}
            </span>
          </div>
        </div>
      </div>
    </section>

    <section class="card">
      <div class="card__header">
        <div class="flex-1">
          <div class="card__title">{{ icon('power', size=17) }} Neustarts</div>
          <div class="card__sub">
            Die letzten {{ events | length }} Neustarts -- ueber den PoE-Port wie per SSH
          </div>
        </div>
      </div>
      {% if events %}
        <div class="table-wrap">
          <table class="table table--compact">
            <thead><tr><th>Zeit</th><th>Methode</th><th>Ausloeser</th><th>Ergebnis</th><th class="numeric">Dauer</th><th>Detail</th></tr></thead>
            <tbody>
              {% for event in events %}
                <tr>
                  <td class="fs-sm nowrap">{{ event.ts | dt }}</td>
                  <td class="fs-sm">
                    {% if event.method == 'ssh' %}{{ pill('SSH', 'info') }}
                    {% else %}{{ pill('PoE-Port', '') }}{% endif %}
                  </td>
                  <td class="fs-sm">{{ event.trigger }} <span class="faint">/ {{ event.actor }}</span></td>
                  <td>
                    {% if event.result == 'ok' %}{{ pill('erfolgreich', 'online') }}
                    {% elif event.result == 'skipped' %}{{ pill('uebersprungen', 'warning') }}
                    {% else %}{{ pill('fehlgeschlagen', 'danger') }}{% endif %}
                  </td>
                  <td class="numeric fs-sm">{{ event.duration_ms or 0 }} ms</td>
                  <td class="fs-xs muted break-all">{{ event.detail }}</td>
                </tr>
              {% endfor %}
            </tbody>
          </table>
        </div>
      {% else %}
        {{ empty_state('Noch keine Neustarts', 'Dieses Geraet wurde noch nie neu gestartet.', 'power') }}
      {% endif %}
    </section>

    <section class="card {{ '' if host_keys else 'card--danger' }}">
      <div class="card__header">
        <div class="flex-1">
          <div class="card__title">
            {{ icon('shield', size=17) }} SSH-Host-Schluessel
            {% if host_keys %}{{ pill('freigegeben', 'online') }}
            {% else %}{{ pill('offen', 'warning') }}{% endif %}
          </div>
          <div class="card__sub">
            Ohne freigegebenen Schluessel verweigern Wartung und Konsole die Verbindung.
          </div>
        </div>
        {% if current_user.has('devices.edit') %}
          <form method="post" action="{{ url_for('devices.probe_host_key', device_id=device.id) }}"
                data-no-guard>
            <input type="hidden" name="{{ csrf_field_name }}" value="{{ csrf_token() }}">
            <button class="btn btn--sm" type="submit" data-busy-label="Lese ...">
              {{ icon('refresh', size=14) }} Auslesen
            </button>
          </form>
        {% endif %}
      </div>
      <div class="card__body stack">
        {% set probed_type = request.args.get('probed_type') %}
        {% set probed_fingerprint = request.args.get('probed_fingerprint') %}
        {% if probed_type and probed_fingerprint and current_user.has('devices.edit') %}
          <div class="alert alert--warning">
            {{ icon('alert', size=18) }}
            <div class="alert__body">
              <div class="alert__title">Gelesener Schluessel</div>
              <div class="mono fs-sm break-all">{{ probed_type }} {{ probed_fingerprint }}</div>
              <p class="fs-sm mt-2">
                Vergleichen Sie den Fingerprint mit einer unabhaengigen Quelle (Konsole am
                Geraet, Inventardokumentation), bevor Sie ihn freigeben.
              </p>
              <form method="post" class="mt-2"
                    action="{{ url_for('devices.trust_host_key', device_id=device.id) }}">
                <input type="hidden" name="{{ csrf_field_name }}" value="{{ csrf_token() }}">
                <input type="hidden" name="key_type" value="{{ probed_type }}">
                <input type="hidden" name="fingerprint" value="{{ probed_fingerprint }}">
                <button class="btn btn--sm btn--primary" type="submit"
                        data-confirm="Diesen Fingerprint dauerhaft als vertrauenswuerdig hinterlegen?"
                        data-confirm-title="Host-Schluessel freigeben" data-confirm-ok="Freigeben"
                        data-confirm-style="primary">Freigeben</button>
              </form>
            </div>
          </div>
        {% endif %}

        {% if host_keys %}
          <dl class="kv fs-sm">
            {% for key in host_keys %}
              <dt>{{ key.key_type }}</dt>
              <dd class="mono fs-xs break-all">{{ key.fingerprint }}</dd>
            {% endfor %}
          </dl>
          {% if current_user.has('devices.edit') %}
            <form method="post"
                  action="{{ url_for('devices.forget_host_key', device_id=device.id) }}"
                  data-no-guard>
              <input type="hidden" name="{{ csrf_field_name }}" value="{{ csrf_token() }}">
              <button class="btn btn--sm btn--ghost" type="submit"
                      data-confirm="Gespeicherte Host-Schluessel dieses Geraets entfernen? Danach muss der Schluessel erneut freigegeben werden."
                      data-confirm-title="Schluessel verwerfen" data-confirm-ok="Verwerfen">
                Verwerfen
              </button>
            </form>
          {% endif %}
        {% else %}
          <p class="muted fs-sm">
            Noch kein Schluessel hinterlegt. Erst lesen, Fingerprint pruefen, dann freigeben.
          </p>
        {% endif %}
      </div>
    </section>
  </div>

  <section class="card">
    <div class="card__header">
      <div class="flex-1"><div class="card__title">{{ icon('info', size=17) }} Stammdaten</div></div>
      {% if current_user.has('devices.edit') %}
        <a class="btn btn--sm" href="{{ url_for('devices.overview') }}">Bearbeiten</a>
      {% endif %}
    </div>
    <div class="card__body">
      <dl class="kv fs-sm">
        <dt>Name</dt><dd>{{ device.name }}</dd>
        <dt>IP</dt><dd class="mono">{{ device.ip }}</dd>
        <dt>MAC</dt><dd class="mono">{{ device.mac }}</dd>
        <dt>Switch</dt>
        <dd>
          {% if device.switch_hostname %}
            <a href="{{ url_for('switches.detail', switch_id=device.switch_id) }}">{{ device.switch_hostname }}</a>
            / {{ device.port }}
          {% else %}<span class="faint">nicht zugeordnet</span>{% endif %}
        </dd>
        <dt>Kategorie</dt><dd>{{ device.category or '&ndash;' | safe }}</dd>
        <dt>Standort</dt><dd>{{ device.location or '&ndash;' | safe }}</dd>
        <dt>Zugangsdaten</dt><dd>{{ device.credential_name or 'keine' }}</dd>
        <dt>Automatischer Neustart</dt><dd>{{ device.auto_restart | yes_no }}</dd>
        <dt>Angelegt</dt><dd>{{ device.created_at | dt }}</dd>
        <dt>Geaendert</dt>
        <dd>{{ device.updated_at | dt }} <span class="faint">von {{ device.updated_by or '-' }}</span></dd>
      </dl>
      {% if device.notes %}<p class="fs-sm muted mt-3">{{ device.notes }}</p>{% endif %}
    </div>
    {% if current_user.has('devices.edit') %}
      <div class="card__footer">
        <form method="post" action="{{ url_for('devices.toggle_active', device_id=device.id) }}" data-no-guard>
          <input type="hidden" name="{{ csrf_field_name }}" value="{{ csrf_token() }}">
          <input type="hidden" name="active" value="{{ '0' if device.is_active else '1' }}">
          <button class="btn btn--sm" type="submit">
            {{ 'Ueberwachung aussetzen' if device.is_active else 'Ueberwachung aktivieren' }}
          </button>
        </form>
      </div>
    {% endif %}
  </section>
</div>
{% endblock %}
