{% extends "components/shell.html" %}

{% block title %}
  <title>Archived Files | {{ g.site_name }}</title>
{% endblock %}

{% block content %}
  <section class="site-section site-section--archives">
    <header class="site-section__header">
      <h1 class="site-section__heading">Archive Files</h1>
    </header>
  </section>

  <section id="password">
    <h2>
      {% if archive.password %}
        Archive password: {{archive.password}}
      {% elif archive.password == "" %}
        Archive needs password, but none was provided. <a id="password-input" style="text-decoration: underline; cursor: pointer" onclick="passwordInputClick()">Click to input</a>
      {% endif %}
    </h2>
  </section>

  {% for file_name in archive.file_list %}
    {% if file_serving_enabled and archive.password %}
      <a href="/archive_files/{{archive.file.hash}}{{archive.file.ext}}?file_name={{file_name}}&password={{archive.password}}">{{file_name}}</a><br>
    {% elif file_serving_enabled and archive.password == None %}
      <a href="/archive_files/{{archive.file.hash}}{{archive.file.ext}}?file_name={{file_name}}">{{file_name}}</a><br>
      {% else %}
      {{file_name}}<br>
    {% endif %}
  {% else %}
    {% if archive %}
      Archive is empty or missing password.
    {% else %}
      File does not exist or is not an archive.
    {% endif %}
  {% endfor %}

  <script>
    async function passwordInputClick() {
      let password = prompt("input password");
      let encodedPassword = encodeURIComponent(password);
      let url = `/api/v1/set_password?file_hash={{archive.file.hash if archive is not none else ''}}&password=${encodedPassword}`;
      let result = await fetch(url).then(resp => resp.json());
      if (result) {
        location.reload();
      } else {
        alert("Invalid password");
      }
    }
  </script>
{% endblock %}
