{% extends "base.html.j2" %}
{% block content %}
<h1>User settings</h1>
<div class="row twelve columns keys">
  <h2>API keys</h2>
  {% with keys = ctx.db.list_nonweb_keys(ctx.uid) %}
  {% if keys %}
  {% for id, name, exp in keys %}
    <div class="row key u-flex">
      <div class="details six columns">
        <span class="key-name">{{ name or 'anonymous' }}</span>
        <span class="key-key">{{ id[:10] }}...</span>
        <span class="key-expiration u-ml-auto">{{ 'Expires in ' if exp else ''}}{{ datetime.fromisoformat(exp) - datetime.now() if exp else 'Never expires' }}</span>
      </div>
      <div class="controls u-flex u-ml-auto">
        <form class="inline" method="none" class="ml-auto">
          <input type="hidden" name="key" value="{{ id }}" id="key{{ loop.index }}">
          <input type="button" value="Copy" onclick="copyKey('#key{{loop.index}}');" />
        </form>
        <form class="inline" method="post" class="ml-auto">
          <input type="hidden" name="action" value="revoke">
          <input type="hidden" name="id" value="{{ id }}">
          <input id="submit" type="submit" value="Revoke"/>
        </form>
      </div>
    </div>
  {% endfor %}
  {% else %}
    <p>No API keys configured.</p>
  {% endif %}
  {% endwith %}
</div>
<div class="row twelve columns keys">
  <h2>Add a key</h2>
  <form method="post">
    <input type="hidden" name="action" value="add">
    <div class="row">
      <div class="row six columns">
        <label for="name">API key name</label>
        <input class="u-full-width" type="text" name="name" value="anonymous" />
      </div>
      <div class="row six columns">
        <label for="ttl">Key lifetime</label>
        <select name="ttl">
          <option value="30d">30 days</option>
          <option value="90d">90 days</option>
          <option value="365d">1y</option>
          <option value="forever">Forever (not recommended)</option>
        </select>
      </div>
    </div>
    <div class="row">
      <input id="submit" type="submit" value="Add" />
    </div>
  </form>
</div>
<script type="text/javascript">
  function copyKey(keySelector) {
    console.log("Hook fired");
    let copyEl = document.querySelector(keySelector);
    console.log(copyEl);
    let copyValue = copyEl.value;
    navigator.clipboard.writeText(copyValue)
  };
</script>
{% endblock %}
