<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="/style.css" rel="stylesheet" type="text/css" media="all">
</head>
<body>
	<div>

<!-- EDIT EXISTING CONFIG -->
  <h2>EDIT EXISTING CONFIG</h2>
		<form action="/home" class='form' method="post">
			{% for n in range(widgLists| length) %}
				<h4>Widget {{n}}</h4>
				{% for key, value in widgLists[n].iteritems() %}
					{{key}}: <input type="text" name="{{key}}{{n}}" value="{{value}}">
					<br>
				{% endfor %}
				<br>
			{% endfor %}

			<h4>System Settings</h4>
			{% for key, value in sysList.iteritems() %}
				{{key}}: <input type="text" name="{{key}}" value="{{value}}">
				<br>
			{% endfor %}
			<br>
			<input type="submit" value="Submit">
		</form>

<!-- ADD NEW WIDGET -->
  <h2>ADD NEW WIDGET</h2>
    <form action="/newWidget" class="form" method="get">
      <h4>New Widget</h4>
      Type: <select id="type" name="type">
        {% for type in widgTypes %}
          <option value="{{type}}">{{type}}</option>
        {% endfor %}
      </select>
      <input type="submit" value="Submit">
    </form>

	</div>



<script>

  /**
   * Retrieves input data from a form and returns it as a JSON object.
   * @param  {HTMLFormControlsCollection} elements  the form elements
   * @return {Object}                               form data as an object literal
   */

  const isValidElement = element => {
    return element.name && element.value;
  };

  const formToJSON = elements => [].reduce.call(elements, (data, element) => {
    if (isValidElement(element)) {
      data[element.name] = element.value;
    }
    return data;
  }, {});

  const handleFormSubmit = event => {
    // Stop the form from submitting since we’re handling that with AJAX.
    event.preventDefault();
    // Call our function to get the form data.
    const data = formToJSON(form.elements);
    /**
    // Demo only: print the form data onscreen as a formatted JSON object.
    const dataContainer = document.getElementsByClassName('results__display')[0];
    // Use `JSON.stringify()` to make the output valid, human-readable JSON.
    dataContainer.textContent = JSON.stringify(data, null, "  ");
    // ...this is where we’d actually do something with the form data...
    **/
    var textContent = JSON.stringify(data, null, "  ");

    var request = new XMLHttpRequest();
    request.open('POST', '/home', true);
    request.setRequestHeader('Content-Type', 'application/json');
    request.send(textContent);

  };


  /*
   * This is where things actually get started. We find the form element using
   * its class name, then attach the `handleFormSubmit()` function to the
   * `submit` event.
   */
  const form = document.getElementsByClassName('form')[0];
  form.addEventListener('submit', handleFormSubmit);

</script>

</body>
</html>