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

{% block page_title %}Benutzer{% endblock %}
{% block page_sub %}{{ users | length }} Konten &middot; Rechte kommen ausschliesslich aus Gruppen{% endblock %}

{% block topbar_extra %}
  {{ search_box('users-table', 'Benutzer suchen ...', count_id='users-visible') }}
  {% if current_user.has('users.create') %}
    <button class="btn btn--primary btn--sm" type="button" data-dialog-open="user-new">
      {{ icon('plus', size=15) }} Konto anlegen
    </button>
  {% endif %}
{% endblock %}

{% block content %}
<section class="card">
  <div class="table-toolbar">
    <span class="muted fs-sm"><span id="users-visible">{{ users | length }}</span> sichtbar</span>
    <span class="table-toolbar__spacer"></span>
    {% if directory_enabled and current_user.has('users.create') %}
      <button class="btn btn--sm" type="button" data-dialog-open="user-directory">
        {{ icon('users', size=15) }} Aus Verzeichnis uebernehmen
      </button>
    {% endif %}
    {% if current_user.is_admin %}
      <a class="btn btn--sm" href="{{ url_for('admin.sessions') }}">{{ icon('activity', size=15) }} Sitzungen</a>
    {% endif %}
  </div>

  <div class="table-wrap">
    <table class="table" id="users-table" data-behavior="sortable">
      <thead>
        <tr>
          <th class="sortable">Benutzer</th>
          <th class="sortable">Name</th>
          <th class="sortable">Quelle</th>
          <th>Gruppen</th>
          <th class="sortable">Status</th>
          <th class="sortable">Letzte Anmeldung</th>
          <th class="actions">Aktion</th>
        </tr>
      </thead>
      <tbody>
        {% for user in users %}
          <tr data-filter-text="{{ user.username }} {{ user.first_name }} {{ user.last_name }} {{ user.email }} {{ user.group_names | join(' ') }}">
            <td>
              <div class="row row--tight">
                <span class="avatar avatar--sm" aria-hidden="true">
                  {{ (user.first_name[:1] ~ user.last_name[:1]) | upper if user.first_name else user.username[:2] | upper }}
                </span>
                <div>
                  <div class="fw-600">{{ user.username }}</div>
                  {% if user.email %}<div class="fs-xs faint">{{ user.email }}</div>{% endif %}
                </div>
              </div>
            </td>
            <td>{{ (user.first_name ~ ' ' ~ user.last_name) | trim or '&ndash;' | safe }}</td>
            <td>
              {% if user.auth_source == 'ldap' %}
                {{ pill('Verzeichnis', 'info') }}
              {% else %}
                {{ pill('Lokal', '') }}
              {% endif %}
            </td>
            <td class="fs-sm">
              {% if user.is_admin %}{{ pill('Administrator', 'accent') }}{% endif %}
              {{ user.group_names | join(', ') or ('&ndash;' | safe if not user.is_admin else '') }}
            </td>
            <td>
              {% if user.is_locked %}{{ pill('Gesperrt', 'danger') }}
              {% else %}{{ pill('Aktiv', 'online') }}{% endif %}
              {% if user.totp_enabled %}<span title="Zwei-Faktor aktiv">{{ icon('lock', size=14) }}</span>{% endif %}
              {% if user.must_change_password %}{{ pill('Passwortwechsel', 'warning') }}{% endif %}
            </td>
            <td class="fs-sm" data-sort-value="{{ user.last_login_at or '' }}">
              {% if user.last_login_at %}
                <span data-relative-time="{{ user.last_login_at }}">{{ user.last_login_at | dt }}</span>
              {% else %}<span class="faint">noch nie</span>{% endif %}
            </td>
            <td class="actions">
              {% if current_user.has('users.edit') %}
                <button class="btn btn--sm btn--ghost" type="button"
                        data-dialog-open="user-edit-{{ user.id }}" aria-label="Bearbeiten">
                  {{ icon('pencil', size=15) }}
                </button>
              {% endif %}
              {% if current_user.has('users.delete') %}
                <form method="post" action="{{ url_for('admin.user_delete', user_id=user.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"
                          data-confirm="Konto {{ user.username }} wirklich loeschen?{% if user.auth_source == 'ldap' %} Verzeichniskonten werden sofort endgueltig entfernt.{% else %} Es landet im Papierkorb.{% endif %}"
                          data-confirm-title="Konto loeschen" data-confirm-ok="Loeschen"
                          aria-label="Loeschen">{{ icon('trash', size=15) }}</button>
                </form>
              {% endif %}
            </td>
          </tr>
        {% endfor %}
      </tbody>
    </table>
  </div>
  {% if not users %}
    {{ empty_state('Keine Konten vorhanden', 'Legen Sie das erste Konto an.', 'users') }}
  {% endif %}
</section>

{{ alert('Rechte werden ausschliesslich ueber Gruppen vergeben. Das Admin-Kennzeichen ist davon
unabhaengig und kann nur von Administratoren gesetzt werden; mindestens ein entsperrtes
Administratorkonto muss immer bestehen bleiben.', 'info') }}
{% endblock %}

{% block dialogs %}
{% if current_user.has('users.create') %}
  {% call modal('user-new', 'Konto anlegen', 'Lokales Konto mit eigenem Passwort') %}
    <form method="post" action="{{ url_for('admin.user_create') }}">
      <input type="hidden" name="{{ csrf_field_name }}" value="{{ csrf_token() }}">
      <div class="modal__body">
        <div class="form-grid">
          {{ field('username', 'Benutzername', required=True, autocomplete='off',
                   extra_class='field--full') }}
          {{ field('first_name', 'Vorname') }}
          {{ field('last_name', 'Nachname') }}
          {{ field('email', 'E-Mail', type='email', extra_class='field--full') }}
          {{ field('password', 'Passwort', type='password', required=True, autocomplete='new-password',
                   hint_text='Mindestens ' ~ policy.min_length ~ ' Zeichen, zwei verschiedene Zeichenarten.',
                   extra_class='field--full') }}
        </div>
        <fieldset class="fieldset">
          <legend>Gruppen</legend>
          <div class="stack stack--tight">
            {% for group in groups %}
              {{ checkbox('group_ids', group.name ~ (' (Standard)' if group.is_default else ''),
                          checked=group.is_default, value=group.id) }}
            {% endfor %}
          </div>
        </fieldset>
        {% if current_user.is_admin %}
          {{ checkbox('is_admin', 'Administrator (darf alles, unabhaengig von Gruppen)') }}
        {% endif %}
        {{ checkbox('must_change_password', 'Passwortwechsel bei der ersten Anmeldung erzwingen', checked=True) }}
      </div>
      <div class="modal__footer">
        <button class="btn" type="button" data-dialog-close>Abbrechen</button>
        <button class="btn btn--primary" type="submit">Konto anlegen</button>
      </div>
    </form>
  {% endcall %}

  {% if directory_enabled %}
    {% call modal('user-directory', 'Aus Verzeichnis uebernehmen',
                  'Konto vorbereiten, damit Gruppen vor der ersten Anmeldung sitzen') %}
      <form method="post" action="{{ url_for('admin.directory_adopt') }}">
        <input type="hidden" name="{{ csrf_field_name }}" value="{{ csrf_token() }}">
        <div class="modal__body">
          {{ field('username', 'Anmeldename im Verzeichnis', required=True, autocomplete='off') }}
          <div class="form-grid">
            {{ field('first_name', 'Vorname') }}
            {{ field('last_name', 'Nachname') }}
          </div>
          {{ field('email', 'E-Mail', type='email') }}
          <fieldset class="fieldset">
            <legend>Gruppen</legend>
            <div class="stack stack--tight">
              {% for group in groups %}
                {{ checkbox('group_ids', group.name, checked=group.is_default, value=group.id) }}
              {% endfor %}
            </div>
          </fieldset>
          {{ alert('Name und E-Mail werden bei der ersten echten Anmeldung aus dem Verzeichnis
          uebernommen und ueberschrieben.', 'info') }}
        </div>
        <div class="modal__footer">
          <button class="btn" type="button" data-dialog-close>Abbrechen</button>
          <button class="btn btn--primary" type="submit">Vorbereiten</button>
        </div>
      </form>
    {% endcall %}
  {% endif %}
{% endif %}

{% if current_user.has('users.edit') %}
  {% for user in users %}
    {% call modal('user-edit-' ~ user.id, 'Konto ' ~ user.username,
                  'Verzeichniskonto' if user.auth_source == 'ldap' else 'Lokales Konto') %}
      <form method="post" action="{{ url_for('admin.user_update', user_id=user.id) }}">
        <input type="hidden" name="{{ csrf_field_name }}" value="{{ csrf_token() }}">
        <div class="modal__body">
          {% if user.auth_source == 'ldap' %}
            {{ alert('Stammdaten und Passwort pflegt der Verzeichnisdienst. Hier lassen sich nur
            Sperre und Gruppen setzen.', 'info') }}
          {% else %}
            <div class="form-grid">
              {{ field('first_name', 'Vorname', value=user.first_name) }}
              {{ field('last_name', 'Nachname', value=user.last_name) }}
            </div>
            {{ field('email', 'E-Mail', value=user.email, type='email') }}
            {{ field('new_password', 'Neues Passwort setzen (optional)', type='password',
                     autocomplete='new-password',
                     hint_text='Setzt das Passwort zurueck, erzwingt einen Wechsel und beendet alle Sitzungen des Kontos.') }}
          {% endif %}
          <fieldset class="fieldset">
            <legend>Gruppen</legend>
            <input type="hidden" name="group_ids_submitted" value="1">
            <div class="stack stack--tight">
              {% for group in groups %}
                {{ checkbox('group_ids', group.name, checked=group.name in user.group_names, value=group.id) }}
              {% endfor %}
            </div>
          </fieldset>
          <div class="stack stack--tight">
            {% if current_user.is_admin and user.id != current_user.id %}
              {{ checkbox('is_admin', 'Administrator', checked=user.is_admin) }}
            {% elif user.is_admin %}
              {{ pill('Administrator', 'accent') }}
            {% endif %}
            {% if user.id != current_user.id %}
              {{ checkbox('is_locked', 'Konto gesperrt', checked=user.is_locked) }}
            {% endif %}
          </div>
        </div>
        <div class="modal__footer modal__footer--split">
          <button class="btn btn--sm" type="submit" formaction="{{ url_for('admin.user_revoke_sessions', user_id=user.id) }}"
                  data-confirm="Alle Sitzungen von {{ user.username }} beenden?"
                  data-confirm-title="Sitzungen beenden" data-confirm-ok="Beenden" data-confirm-style="danger">
            Sitzungen beenden
          </button>
          <span class="row row--tight">
            <button class="btn" type="button" data-dialog-close>Abbrechen</button>
            <button class="btn btn--primary" type="submit">Speichern</button>
          </span>
        </div>
      </form>
    {% endcall %}
  {% endfor %}
{% endif %}
{% endblock %}
