{% extends "spider_base/base.html" %}
{# inherits NOT from nouc_base #}

{% load i18n static spider_rdf spider_base %}

{% block title %}{% if object %}{% if object.is_index %}{% blocktrans trimmed %}
Change Login Protection{% endblocktrans %}{% else %}{% blocktrans trimmed %}
    Change Component
  {% endblocktrans %}{% endif %}{% else %}{% blocktrans trimmed %}
  Create Component
{% endblocktrans %}{% endif %}{% endblock %}


{% block extrahead %}
{{block.super}}
<script src="{% static 'node_modules/qrcode/build/qrcode.min.js' %}"></script>
{{form.media|safe}}
{% endblock %}
{# public_meta not required because it will never be used #}

{% block main_classes %}{{block.super}} {% if not object %}w3-sand{% else %}w3-card-4 color-front-{{object.strength}}{% endif %} spkc-content{% endblock %}
{% block body_class %}{{block.super}} {% if not object %}w3-light-grey{% else %}color-back-{{object.strength}}{% endif %}{% endblock %}


{% block content %}
  <div class="w3-padding" style="min-height:120px">
    <span class="w3-left">
    {% if object %}
      <a class="w3-block" style="margin-bottom:5px" href="{% url 'spider_base:ucontent-list' token=object.token %}">
        <i class="fas fa-arrow-up" style="margin-right:10px" aria-hidden="true"></i>{% trans "Contents" %}
      </a>
    {% endif %}
      <a class="w3-block" style="margin-bottom:5px" href="{% url 'spider_base:ucomponent-list' %}">
        <i class="fas {% if object %}fa-angle-double-up{% else %}fa-arrow-up{% endif %}" style="margin-right:10px" aria-hidden="true"></i>{% trans 'Own' %}
      </a>
    </span>
    {% if object %}
      <span class="w3-right w3-left-align">
        <a class="w3-block" style="margin-bottom:5px" onclick="if(document.readyState === 'complete'){open_qrmodal();}; return false;" href="#">
          <i class="fas fa-file-export" style="margin-right:10px" aria-hidden="true"></i>{% trans 'Link/Export' %}
        </a>
        {% if not object.is_index %}
          <div style="margin-bottom:5px">
            <a href="{% url 'spider_base:ucomponent-delete' token=object.token %}">
              <i class="fas fa-trash" style="margin-right:10px" aria-hidden="true"></i>{% trans 'Delete' %}
            </a>
          </div>
        {% endif %}
        <div>
          <i class="fas fa-lock" style="margin-right:10px" aria-hidden="true"></i>{% trans "Strength" %}: <data property="spkc:strength" datatype="xsd:integer">{{object.strength}}</data>
        </div>
      </span>
    {% endif %}
    <h1 class="w3-center">
      {% if object and form.instance.is_index %}
        {% trans 'Change Login Protection' %}
      {% elif object %}
        {% blocktrans trimmed %}
          Change Component
        {% endblocktrans %}: <b>{{form.instance}}</b>
      {% else %}
        {% trans 'Create new Component' %}
      {% endif %}
    </h1>
  </div>
  {% if object %}
    <form hidden="hidden" id="deleteForm" onsubmit="return delete_token(event)" method="post" action='{% url "spider_base:token-delete" token=object.token %}'>
      {% csrf_token %}
    </form>
  {% endif %}
  {% include "spider_base/partials/form_errors.html" with form=form %}
  <form class="w3-padding" id="componentForm" action="{{ request.get_full_path }}" encdata="multipart/form-data" method="post">
    {% csrf_token %}
    <data hidden="hidden" property="type" datatype="xsd:string">Component</data>
    {% if object %}
    <fieldset class="w3-padding">
      <legend>
        <h2>
          {% trans 'Add new content' %}
        </h2>
      </legend>
      <div class="w3-white w3-border">
      {% include "spider_base/partials/content_variants_box.html" with open=True uc=object %}
      </div>
    </fieldset>
    {% endif %}
    <fieldset style="width:100%">
      <legend>
        <h2>
        {% if form.instance.id and form.instance.is_index %}
          {% trans 'Login Protection' %}
        {% else %}
          {% trans 'User Component' %}
        {% endif %}
        </h2>
      </legend>
      {% if object %}
        <div style="overflow-y: auto; max-height:300px">
          <table class="w3-table-all" id="token_container">
            <thead>
              <tr>
                <th colspan="3" class="w3-center"><h3>{% trans 'Active Tokens' %}</h3></th>
              </tr>
              <tr>
                <th>{% trans 'Token' %}</th>
                <th>{% trans 'Valid till / Referrer' %}</th>
                <th>{% trans 'Delete' %}</th>
              </tr>
            </thead>
            <tbody>
              {% for token in object.authtokens.all %}
                {% token_expires object token as expire_date %}
                <tr>
                  <td style="word-break:break-all">
                    {{token}}
                  </td>
                  <td>
                    {% if token.persist >= 0 %}
                      <span class="w3-center">&infin;</span><br/>{{token.referrer}}
                    {% else %}
                      {{expire_date|date:"D, d/m/Y"}}{% if token.referrer %}<br/>{{token.referrer}}{% endif %}
                    {% endif %}
                  </td>
                  <td>
                    <input form="deleteForm" type="checkbox" name="token" onclick='updateAllSelector(this)' value="{{token.id}}"/>
                  </td>
                </tr>
              {% endfor %}
            </tbody>
          <tbody>
            <tr class="w3-light-grey">
              <td></td><td></td>
              <td>
                {# onchange would be also triggered by reset, so use click instead #}
                <input style="margin-left:10px" id="deleteAllSelector" type="checkbox" onclick='toggleAll(this);'/>
              </td>
            </tr>
          </tbody>
          </table>
        </div>
        <div style="height:50px">
          <button class="w3-button w3-grey w3-right w3-hover-red" form="deleteForm"><i class="fas fa-trash" aria-hidden="true" style="margin-right:10px"></i>{% trans 'Delete' %}</button>
        </div>
      {% endif %}
      {% include "spider_base/partials/base_form.html" with form=form %}
    </fieldset>
    {% if form.instance.id %}
    <button class="w3-button w3-grey">
      {% trans "Change" %}
    </button>
    {% endif %}
    <fieldset style="overflow-y: auto; max-height:600px">
      <legend style="bottom:100px;"><h2>{% trans 'Protections' %}</h2></legend>
      {% for prot in form.protections %}
        <div class="protection-wrapping">
          <div class="w3-padding-small w3-card w3-white">
            <h1 class="w3-center" style="word-break:break-word">{{prot}}</h1>
            {% include "spider_base/partials/base_form.html" with form=prot %}
          </div>
        </div>
      {% empty%}
        <div class="protection-wrapping">
          <div class="w3-padding-small w3-card w3-orange">{% trans 'No protections: create component first' %}</div>
        </div>
      {% endfor %}
    </fieldset>
    <button class="w3-button w3-grey">
      {% if form.instance.id %}{% trans "Change" %}{% else %}{% trans "Create" %}{% endif %}
    </button>
    {% if object %}
      <a class="w3-right" href="{% url 'spider_base:ucontent-list' token=object.token %}">
        {% trans "Contents" %}
      </a>
    {% endif %}
  </form>
{% endblock %}

{% block outercontent %}
{% if object %}
  {% url 'spider_base:ucontent-export' token=object.token as exportlink %}
  {% include "spider_base/partials/modalpresenter.html" %}
  <script>
    let allselector=document.getElementById("deleteAllSelector");
    let deleteform=document.getElementById("deleteForm");
    async function toggleAll(caller){
      let state=caller.checked;

      if (deleteform.token.length){
        for (let count=0; count < deleteform.token.length; count++){
          deleteform.token[count].checked = state;
        }
      } else {
        deleteform.token.checked = state;
      }
    }
    async function updateAllSelector(caller){
      let state = true;
      if (caller === null || caller.checked==true){
        if (deleteform.token.length){
          for (let count=0; count < deleteform.token.length; count++)
          {
            if (deleteform.token[count].checked == false)
            {
              state=false;
              break;
            }
          }
        } else {
          state = deleteform.token.checked;
        }
      } else {
        state=false;
      }
      allselector.checked = state;
    }
    async function delete_token(event){
      event.preventDefault()
      let tokens = []
      if (event.target.token.length){
        for (let count=0; count < event.target.token.length; count++)
        {
            if (event.target.token[count].checked == true)
            {
                tokens.push(event.target.token[count].value)
            }
        }
      } else {
          if (event.target.token.checked == true)
          {
              tokens.push(event.target.token.value)
          }
      }
      let body = new URLSearchParams();
      for(let count=0; count < tokens.length; count++){
        body.append("tokens", tokens[count]);
      }
      req = new Request('{% url "spider_base:token-delete" token=object.token %}', {
          method: 'POST',
          body: body,
          credentials: "same-origin",
          headers: {
             "X-CSRFToken": event.target.csrfmiddlewaretoken.value,
         }
      });
      await fetch(req)
        .then(function(response) { return response.json(); })
        .then(function(data) {
        let tbody = document.getElementById("token_container").tBodies[0];
        while(tbody.rows.length != 0) {
          tbody.deleteRow(0);
        }
        for(let count=0; count<data["tokens"].length; count++){
          let row = tbody.insertRow();
          let cell1 = row.insertCell()
          cell1.style.wordBreak = "break-all";
          cell1.innerText = data["tokens"][count].name
          let cell2 = row.insertCell()
          if (!data["tokens"][count].expires){
            cell2.innerText = `\u221E\n${encodeURI(data["tokens"][count].referrer)}`
          } else {
            let date = new Date(data["tokens"][count].expires);
            // D d M Y
            cell2.innerText = `${date.toLocaleDateString("en-GB", {
              weekday: 'short', year: 'numeric', month: 'numeric', day: 'numeric'
            })}\n${data["tokens"][count].referrer}`
          }
          let cell3 = row.insertCell()
          cell3.innerHTML = `<input form="deleteForm" type="checkbox" name="token" onclick='updateAllSelector(this)' value="${data["tokens"][count].id}"></input>`
        }
        allselector.checked = false;
        // renew authtoken of modalpresenter
        auth_token = data["admin"]
      })
      return false;
    };
  </script>
{% endif %}
{% endblock %}
