{% extends "base" %}

{% block content %}

<script src="/static/js/qrcode.min.js"></script>

<section id="contact" class="">
  <div class="container">
    <header>
      <h2>Add A Peer</h2>
    </header>
    <p>Use this form to add new peers to the WireGuard VPN. Input an IP address for this peer to use within the server's network CIDR range:</br><strong>{% if state.interface %}{{ state.interface }}{% else %}not defined{% endif %}</strong></p>
    <form id="peer-form" action="/save-peer-config" method="post">
      <input type="text" name="ipaddr" id="input-ipaddr" placeholder="Enter an IP address for the peer">
      <!-- <input type="submit" value="Add Peer"> -->
    </form>
    <br>
    <pre id="peer-config" class="code"></pre>
    <div id="qrcode"></div>
  </div>
</section>

<script type="text/javascript">

var input_ip_address = document.getElementById('input-ipaddr');
var peer_config_element = document.getElementById('peer-config');
var qr_code_element = document.getElementById('qrcode');
var current_text = input_ip_address.value;
// var qr_code = new QRCode(qr_code_element, get_templated(current_text));
var qr_code = new QRCode(qr_code_element, {
    text: get_templated(current_text),
    colorDark : "#7d2220",
    colorLight : "#ffffff",
    correctLevel : QRCode.CorrectLevel.H
});
var timeout = null;

function get_templated(ip_addr){
  var peer_config = `[Interface]
PrivateKey = {{ privkey }}
Address = ${ip_addr}/32
DNS = {{ state.dns }}

[Peer]
PublicKey = {{ state.pubkey }}
AllowedIPs = 0.0.0.0/0
Endpoint = {{ state.endpoint }}:{{ state.port }}
PersistentKeepalive = 21`;
  return peer_config;
}

function update_meta(){
  var new_text = input_ip_address.value;
  if (new_text==current_text) return; else current_text=new_text;
  var peer_config = get_templated(current_text);
  peer_config_element.innerHTML = peer_config;
  qr_code.clear();
  qr_code.makeCode(peer_config);
}

function eventHandler(){
  if(timeout) clearTimeout(timeout);
  timeout=setTimeout(update_meta, 50);
}

input_ip_address.onkeydown=input_ip_address.onkeyup=input_ip_address.onclick=eventHandler;
input_ip_address.focus();
peer_config_element.innerHTML = get_templated(current_text);
</script>

{% endblock content %}
