{% extends "reset_password_base.html" %}
{% block title %}Reset Password{% endblock %}

{% block main %}
<div id="form">
  <h1>Reset password for {{username}}</h1>
  <input type="password" id="password"></input>
  <button id="submit" onclick="submit()">Submit</button>
</div>
<div id="error" class="error" style="display:none;margin-top:2em;">
</div>
<div id="success" class="success" style="display:none;">
  <img width="200" src="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiA/PjxzdmcgaWQ9IkxheWVyXzEiIHN0eWxlPSJlbmFibGUtYmFja2dyb3VuZDpuZXcgMCAwIDYxMiA3OTI7IiB2ZXJzaW9uPSIxLjEiIHZpZXdCb3g9IjAgMCA2MTIgNzkyIiB4bWw6c3BhY2U9InByZXNlcnZlIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIj48c3R5bGUgdHlwZT0idGV4dC9jc3MiPgoJLnN0MHtmaWxsOiM0MUFENDk7fQo8L3N0eWxlPjxnPjxwYXRoIGNsYXNzPSJzdDAiIGQ9Ik01NjIsMzk2YzAtMTQxLjQtMTE0LjYtMjU2LTI1Ni0yNTZTNTAsMjU0LjYsNTAsMzk2czExNC42LDI1NiwyNTYsMjU2UzU2Miw1MzcuNCw1NjIsMzk2TDU2MiwzOTZ6ICAgIE01MDEuNywyOTYuM2wtMjQxLDI0MWwwLDBsLTE3LjIsMTcuMkwxMTAuMyw0MjEuM2w1OC44LTU4LjhsNzQuNSw3NC41bDE5OS40LTE5OS40TDUwMS43LDI5Ni4zTDUwMS43LDI5Ni4zeiIvPjwvZz48L3N2Zz4=">
  <div>Password successfully updated</div>
</div>


<script>
  function submit() {
    const inputPw = document.getElementById("password");
    const pw = inputPw.value;
    const urlParams = new URLSearchParams(window.location.search);
    const jwt = urlParams.get('jwt');
    fetch(`/api/users/-/password/reset/?jwt=${jwt}`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ new_password: pw })
    })
      .then(response => {
        switch (response.status) {
          case 201:
            handleSuccess();
            break;
          case 400:
            handleError("Error: Password not accepted");
            break;
          default:
            handleError("Unexpected error");
        }
      });
  }

  function handleSuccess() {
    const divErr = document.getElementById("error");
    const divSuccess = document.getElementById("success");
    const divForm = document.getElementById("form");
    divErr.style.display = 'none';
    divForm.style.display = 'none';
    divSuccess.style.display = 'block';
  }

  function handleError(msg) {
    const divErr = document.getElementById("error");
    divErr.innerHTML = msg;
    divErr.style.display = 'block';
  }
</script>
{% endblock %}
