{% extends 'base.html' %}

{% block title %}Proximity Demo - Index{% endblock title %}

{% block content %}
<div class="container">
    <h1 id="titleH1">Editing tag #{{ tag_id }}</h1>
    <div class="row">
        <form>
            <div class="row">
                <div class="six columns">
                    <label for="nameInput">Tag Name</label>
                    <input class="u-full-width" type="text" placeholder="" id="nameInput">
                </div>
            </div>
            <input id="submitBtn" class="button-primary" type="submit" value="Submit">
        </form>
    </div>
</div>
{% endblock content %}

{% block js %}
<script>
  'use strict';
  document.addEventListener("DOMContentLoaded", function (){
    fetch('/api/zones/{{ zone_id }}').
    then(response => response.json()).
    then(data => {
        console.log(data);
        document.getElementById('titleH1').innerText =
            "Editing zone: " + data.name;
        document.getElementById('nameInput').value = data.name;
    });
  });
  const orig_name = document.getElementById('nameInput').value;
  document.getElementById('submitBtn').addEventListener('click', function(evt) {
      evt.preventDefault();
      const new_name = document.getElementById('nameInput').value;
      if (new_name === orig_name) {
          return;
      }
      fetch('/api/zones/{{ zone_id }}', {
          method: 'PATCH',
          headers: {'Content-Type': 'application/json'},
          body: JSON.stringify({
              name: new_name,
          })
      }).then(response => {
          if (response.ok === true) {
              location.replace('/demo/');
              return;
          }
          alert("Update failed: " + response.statusText);
      })
  })
</script>
{% endblock js%}
