{% 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 %}


{# 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">
    {% for name in machine_variants %}
      <data hidden="hidden" property="spkc:create:name" datatype="xsd:string">{{name}}</data>
    {% endfor %}
    <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 rel="nofollow" class="w3-block" style="margin-bottom:5px" onclick="if(document.readyState === 'complete'){return open_qrmodal(event);}; return false;" href="#">
          <i class="fas fa-file-export" style="margin-right:10px" aria-hidden="true"></i>{% trans 'Share' %}
        </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-admin-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">
    <input type="hidden" property="spkc:csrftoken" name="csrfmiddlewaretoken" datatype="xsd:string" content="{{csrf_token}}" value="{{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="4" class="w3-center"><h3>{% trans 'Active Tokens' %}</h3></th>
              </tr>
              <tr>
                <th>{% trans 'Token' %}</th>
                <th>{% trans 'Valid till / Referrer' %}</th>
                <th><i class="fas fa-bell w3-hide-medium" aria-hidden="true"></i><span class="w3-hide-medium w3-hide-small" style="width:10px"> </span><span class="w3-hide-small">{% trans 'View Update Request' %}</span></th>
                <th><i class="fas fa-trash w3-hide-medium" aria-hidden="true"></i><span class="w3-hide-medium w3-hide-small" style="width:10px"> </span><span class="w3-hide-small">{% trans 'Delete' %}</span></th>
              </tr>
            </thead>
            <tbody>
            </tbody>
          <tbody>
            <tr class="w3-light-grey">
              <td></td><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 %}
    {# fieldsets don't allow horizontal scrolling #}
    <h2>{% trans 'Protections' %}</h2>
    <div class="w3-padding w3-border" style="overflow-y: auto; max-height:600px">
      {% 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 %}
    </div>
    <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 %}
  {% include "spider_base/partials/share_presenter.html" with uc=object %}
  <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 update_token(form, data=null){
      let tokens = [];
      let fetch_req;
      if (data===null){
        if (form.token){
          if (form.token.length){
            for (let count=0; count < form.token.length; count++)
            {
                if (form.token[count].checked == true)
                {
                    tokens.push(form.token[count].value)
                }
            }
          } else {
              if (form.token.checked == true)
              {
                  tokens.push(form.token.value)
              }
          }
        }
        let body = new URLSearchParams();
        for(let count=0; count < tokens.length; count++){
          body.append("delete_tokens", tokens[count]);
        }
        req = new Request('{% url "spider_base:token-admin-delete" token=object.token %}?{{sanitized_GET}}', {
            method: 'POST',
            body: body,
            credentials: "same-origin",
            headers: {
               "X-CSRFToken": form.csrfmiddlewaretoken.value,
            }
        });
        fetch_req = fetch(req).then(
          function(response) {
            if (!response.ok){
              return null;
            }
            return response.json().then(function (d){
              d["tokens"].sort(function(a, b){
                if (a.needs_confirmation && !b.needs_confirmation){
                  return -1;
                }
                if (a.admin_key && !b.admin_key){
                  return -1;
                }
                if (a.id < b.id){
                  return -1;
                } else if (a.id > b.id){
                  return 1;
                } else {
                  return 0;
                }
              });
              return d;
            });
          },
          function(response) {
            return null;
          }
        );
      } else {
        fetch_req = Promise.resolve(data);
      }

      let tbody = document.getElementById("token_container").tBodies[0];
      while(tbody.rows.length != 0) {
        tbody.deleteRow(0);
      }
      data = await fetch_req;
      if (data===null){
        return;
      }
      data["tokens"].sort(function(a, b){
        if (a.needs_confirmation && !b.needs_confirmation){
          return -1;
        }
        if (a.admin_key && !b.admin_key){
          return -1;
        }
        if (a.id < b.id){
          return -1;
        } else if (a.id > b.id){
          return 1;
        } else {
          return 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()
        if (data["tokens"][count].request_intentions){
          cell3.innerHTML = `<a href="{% url 'spider_base:token-confirm-update-request' %}?next={{request.path|urlencode}}&{{sanitized_GET}}&refid=${data["tokens"][count].id}" class="w3-button w3-blue"><i class="fas fa-edit" aria-hidden="true"></i></a>`
        }
        let cell4 = row.insertCell()
        cell4.innerHTML = `<input form="deleteForm" type="checkbox" name="token" onclick='updateAllSelector(this)' value="${data["tokens"][count].id}"></input>`
      }
      allselector.checked = false;
      return false;
    };

    async function delete_token(event){
      event.preventDefault()
      return await update_token(event.target)
    }

    document.addEventListener("DOMContentLoaded", async function(){
      await update_token(deleteform);
    })
    document.addEventListener("spider_token_updated", async function(event){
      await update_token(deleteform, event.data);
    });
  </script>
{% endif %}
{% endblock %}
