{% load i18n %}

{# z-index important for trumbowyg, set higher if not enough #}
<div id="share_modal_presenter" class="w3-modal" style="height:100%; z-index:100;">
  <div class="w3-modal-content">
    <header class="w3-container w3-teal">
      <span onclick="close_qrmodal(event)"
      class="w3-button w3-black w3-display-topright">&times;</span>
      <h2>{% trans "Share" %}</h2>
    </header>
    <div style="margin-bottom:10px">
      <div class="w3-container w3-cell w3-mobile">
        <canvas id="share_qrcanvas"></canvas>
      </div>
    </div>
    <div class="w3-container w3-text-black">
      <div class="" id="share_remotelink_wrapper"  style="word-break: break-all">
        {# escapejs is a weaker escape, don't use it #}
        <a type="text" rel="nofollow" href="{{remotelink}}{{remotelink_extra}}" id="share_remotelink"></a>
        <span style="margin-left:10px;padding:1px 10px" id="share_copy_clipboard" class="w3-round w3-grey">
          <i class="fas fa-clipboard" aria-label="{% trans 'Clipboard' %}"></i>
        </span>
      </div>
      <div style="padding-bottom:20px">
        <h2>{% trans "Select Token "%}</h2>
        <select id="share_token_selector">
          <option value="" selected=""></option>
          {% if request.auth_token %}<option value="{{request.auth_token.token}}">{{request.auth_token.token}}</option>{% endif %}
        </select>
        {% if request.is_special_user %}
        <div style="padding-top:10px">
          <button class="w3-button w3-grey" id="share_add_button" value="add">
            <i class="fas fa-plus-circle" style="margin-right:10px" aria-hidden="true"></i>{% trans 'Add' %}
          </button>
          <button class="w3-button w3-grey" id="share_refresh_button" value="refresh">
            <i class="fas fa-sync" style="margin-right:10px" aria-hidden="true"></i>{% trans 'Refresh' %}
          </button>
          <button class="w3-button w3-grey" id="share_delete_button" value="delete">
            <i class="fas fa-trash" style="margin-right:10px" aria-hidden="true"></i> {% trans 'Delete' %}
          </button>
        </div>
        {% endif %}
      </div>
    </div>
  </div>
</div>

<script type="text/javascript">
let remotelink = document.getElementById('share_remotelink');
let qrcanvas = document.getElementById('share_qrcanvas');
let presenter = document.getElementById('share_modal_presenter');
let token_selector = document.getElementById('share_token_selector');
let share_copy_clipboard = document.getElementById('share_copy_clipboard');

function update_qrmodal(){
  {# escapejs is a weaker escape, don't use it #}
  let _remotelink = "{{remotelink}}{{remotelink_extra}}";
  if(token_selector.value != ""){
    _remotelink = `${_remotelink}token=${token_selector.options[token_selector.options.selectedIndex].text}&`;
  }
  remotelink.href = _remotelink;
  remotelink.text = _remotelink;
  QRCode.toCanvas(
    qrcanvas, _remotelink, { errorCorrectionLevel: 'H' },
    function (error) {
      if (error)
        console.error(error)
    }
  )
  return false;
}


async function link_to_clipboard(event){
  await navigator.clipboard.writeText(remotelink.href);
  share_copy_clipboard.firstElementChild.classList.replace("fa-clipboard", "fa-clipboard-check");
  share_copy_clipboard.classList.replace("w3-grey", "w3-green");
  await new Promise((resolve) => setTimeout(resolve, 3000));
  share_copy_clipboard.classList.replace("w3-green", "w3-grey");
  share_copy_clipboard.firstElementChild.classList.replace("fa-clipboard-check", "fa-clipboard");
  return false;
}
share_copy_clipboard.addEventListener("click", link_to_clipboard);

async function update_share_tokens(event){
  if(token_selector.disabled==true)
    return;
  token_selector.disabled=true;
  let body = new URLSearchParams();
  if(event){
    event.preventDefault();
    if (event.target.value == "delete"){
      body.append("delete_tokens", token_selector.value);
    } else if(event.target.value == "add") {
      body.append("add_token", true);
    }

  }
  req = new Request('{% url "spider_base:token-admin-share" token=uc.token %}', {
      method: 'POST',
      body: body,
      credentials: "same-origin",
      headers: {
         "X-CSRFToken": "{{csrf_token}}",
      }
  });
  let fetch_req = fetch(req).then(function(response) { return response.json(); })
  while(token_selector.options.length != 1) {
    token_selector.options.remove(token_selector.options.length-1);
  }
  data = await fetch_req;
  for(let count=0; count<data["tokens"].length; count++){
    let token = data["tokens"][count];
    if (token.created){
      token_selector.options.add(new Option(token.name, token.id, true, true));
    } else {
      token_selector.options.add(new Option(token.name, token.id));
    }
  }
  token_selector.disabled=false;
  update_qrmodal();
  return false;
};

document.getElementById('share_delete_button').addEventListener("click",update_share_tokens);
document.getElementById('share_add_button').addEventListener("click",update_share_tokens);
document.getElementById('share_refresh_button').addEventListener("click",update_share_tokens);

token_selector.addEventListener("change",update_qrmodal);

async function open_qrmodal(event){
  if(event)
    event.preventDefault();
  await update_share_tokens(null);
  update_qrmodal();
  presenter.style.display='block';
  return false;
}


function close_qrmodal(event){
  if(event)
    event.preventDefault()
  presenter.style.display='none'
}
</script>
