{% extends "registration/base.html" %}

{% load i18n core_tags form_tags static %}

{% block extra_css %}
  <link rel="stylesheet" type="text/css" href="{% static 'css/login.css' %}" />
{% endblock %}

{% block main_content %}
  <div class="login-box">
    <h2>{% translate "Verification" %}</h2>
    {% if show_method_selection %}
      <div id="methodSelection">
        {% if totp_device %}
          <button class="btn btn-primary" onclick="showTOTP()">{% translate "Use TOTP/backup code" %}</button>
        {% endif %}
        {% if webauthn_device %}
          <button class="mt btn btn-primary" onclick="showWebAuthn()">{% translate "Use Webauthn device" %}</button>
        {% endif %}
      </div>
    {% endif %}
    <div id="totp_form" {% if show_method_selection or not totp_device %}style="display:none;"{% endif %}>
      <form method="post" action="{% url 'core:2fa_verify' %}">
        {% csrf_token %}
        <input type="hidden" id="id_next" name="next" value="{{ nextlocation }}">
        <div class="input-group{% if form.tfa_code.errors %} error{% endif %}">
          <label>{% translate "One-time password" %}</label>
          <input id="id_tfa_code" name="tfa_code" required autofocus>
          <span class="error-message">
            {% for error in form.tfa_code.errors %}
              {{ error }}
            {% endfor %}
          </span>
          <p class="help-block">
            {% blocktranslate trimmed %}
              Enter the code from the two-factor app on your mobile
              device. If you've lost your device, you may enter one of your
              recovery codes.
            {% endblocktranslate %}
          </p>
        </div>
        <button class="btn btn-primary" type="submit">{% translate "Verify code" %}</button>
      </form>
      {% if show_method_selection %}
        <button class="mt btn" onclick="backToSelection()">{% translate "Back" %}</button>
      {% endif %}
    </div>
    <div id="webautn_form" {% if show_method_selection or not webauthn_device %}style="display:none;"{% endif %}>
      <button class="btn btn-primary" onclick="useWebAuthn()">{% translate "Log using Webauthn" %}</button>
      {% if show_method_selection %}
        <button class="mt btn" onclick="backToSelection()">{% translate "Back" %}</button>
      {% endif %}
    </div>
  </div>
{% endblock %}

{% block extra_js %}
  <script type="module" defer>
  import {
    get,
    parseRequestOptionsFromJSON,
  } from "{% static 'js/webauthn-json.browser-ponyfill.js' %}"

  function showTOTP() {
    document.getElementById("totp_form").style.display = 'block'
    document.getElementById("methodSelection").style.display = 'none'
  }
  window.showTOTP = showTOTP

  function backToSelection() {
    document.getElementById("totp_form").style.display = 'none'
    document.getElementById("webautn_form").style.display = 'none'
    document.getElementById("methodSelection").style.display = 'block'
  }
  window.backToSelection = backToSelection

  function showWebAuthn() {
    document.getElementById("webautn_form").style.display = 'block'
    document.getElementById("methodSelection").style.display = 'none'
  }
  window.showWebAuthn = showWebAuthn

  async function useWebAuthn() {
    const csrf = getCookie('csrftoken')
    const request = await fetch("{% url 'core:fido_auth_begin' %}", {
      method: 'POST',
      headers: { "X-CSRFToken": csrf, 'Content-Type': 'application/json' }
    })
    if (!request.ok) {
      throw new Error('No credential available to authenticate!')
    }
    let json = await request.json()
    let options = parseRequestOptionsFromJSON(json)

    let response = await get(options);
    let params = new URLSearchParams(window.location.search)
    let url = "{% url 'core:fido_auth_end' %}"
    if (params.has('next')) {
      url += `?next=${encodeURIComponent(params.get('next'))}`
    }
    let result = await fetch(url, {
      method: 'POST',
      headers: { "X-CSRFToken": csrf, 'Content-Type': 'application/json'},
      body: JSON.stringify(response),
    })
    json = await result.json()
    location.href = json.next
  }
  window.useWebAuthn = useWebAuthn

  function getCookie(cname) {
    const name = cname + "="
    const decodedCookie = decodeURIComponent(document.cookie)
    const ca = decodedCookie.split(';')
    for(let i = 0; i <ca.length; i++) {
      let c = ca[i]
      while (c.charAt(0) == ' ') {
        c = c.substring(1)
      }
      if (c.indexOf(name) == 0) {
        return c.substring(name.length, c.length)
      }
    }
    return ""
  }
  </script>
{% endblock %}
