<script>


function addTrigger()
{
  var field_area = document.getElementById("triggers");
  var all_inputs = field_area.getElementsByTagName("li"); //Get all the input fields in the given area.
  var count = all_inputs.length;
  var li = document.createElement("li");
  li.innerHTML = '<select name="analog" id="analogid" placeholder="Select Input">' +
                    {% for _,dev in ipairs(deviceinfo) do %}
                    '<optgroup label="{{dev.name}} - {{dev.serial}}">' +
                       {% for _,aport in ipairs(dev.analogs) do %}
                       '<option value="{{dev.serial}}:{{aport}}">{{aport}}</option>' +
                       {% end %}
                    '</optgroup>' +
                    {% end %}
                 '</select> ' +
                 '<select name="operation" id="ltgtid">' +
                    '<option value="lt">Less Than</option>' +
                    '<option value="gt">Greater Than</option>' +
                 '</select> ' +
                 '<input type="number" name="value" id="valueid" step="any" placeholder="0.0"> ' +
                 '<a style="cursor:pointer; color:blue;" onclick="removeTrigger(this)"> '+
                     '<img src="images/trash.png" alt="Delete" title="Delete"/> '+
                 '</a>';

  field_area.appendChild(li);
}

function removeTrigger(node)
{
  node.parentNode.parentNode.removeChild(node.parentNode);
}

function addTimeLimit()
{
  var field_area = document.getElementById("timelimits");
  var all_inputs = field_area.getElementsByTagName("li"); //Get all the input fields in the given area.
  var count = all_inputs.length;
  var li = document.createElement("li");

  li.innerHTML = 
        '<select name="mustrun">' +
            '<option value="false">Must Not Run</option>' +
            '<option value="true">Must Run</option>' +
        '</select> ' +
        'Su<input type="checkbox" id="sun0" name="sun"> '  +
        'Mo<input type="checkbox" id="mon0" name="mon"> ' +
        'Tu<input type="checkbox" id="tue0" name="tue"> ' +
        'We<input type="checkbox" id="wed0" name="wed"> ' +
        'Th<input type="checkbox" id="thu0" name="thu"> ' +
        'Fr<input type="checkbox" id="fri0" name="fri"> ' +
        'Sa<input type="checkbox" id="sat0" name="sat"> ' +
        'From <input type="time" name="starttime"> ' +
        'To <input type="time" name="endtime"> ' +
        '<a style="cursor:pointer; color:blue;" onclick="removeTimeLimit(this)"> ' +
          '<img src="images/trash.png" alt="Delete" title="Delete"/> ' +
        '</a>';
  
  field_area.appendChild(li);
}

function removeTimeLimit(node)
{
  node.parentNode.parentNode.removeChild(node.parentNode);
}


function submitData()
{
  const form =  document.getElementById('duraform');
  const timelimits = form.querySelectorAll('ul[name="timelimits"] li');
  const triggers = form.querySelectorAll('ul[name="triggers"] li');
  
  var output_data = form.outputselect.value.split(':')
   
  const data = {
    output: {deviceid: output_data[0],
             label: output_data[1]},
    triggers: [],
    timelimits: []
   };
   
   //Extract Triggers
   for (var i = 0; i < triggers.length; i++)
   {
      var trigger = {type: "analog"};
      var trigger_label = triggers[i].querySelectorAll('select[name="analog"]')[0].value.split(':');
      trigger.deviceid = trigger_label[0];
      trigger.label = trigger_label[1];
      trigger.operation = triggers[i].querySelectorAll('select[name="operation"]')[0].value;
      trigger.value = triggers[i].querySelectorAll('input[name="value"]')[0].value;
      data.triggers.push(trigger);
   }
   
   
   //Extract Timelimits

   for (var i = 0; i < timelimits.length; i++)
   {
       var tl = {};
       tl.mustrun = timelimits[i].querySelectorAll('select[name="mustrun"]')[0].value;
       tl.days = [];
       
       if(timelimits[i].querySelectorAll('input[name="sun"]')[0].checked)
       {
        tl.days.push(0);
       }
       if(timelimits[i].querySelectorAll('input[name="mon"]')[0].checked)
       {
        tl.days.push(1);
       }
       if(timelimits[i].querySelectorAll('input[name="tue"]')[0].checked)
       {
        tl.days.push(2);
       }
       if(timelimits[i].querySelectorAll('input[name="wed"]')[0].checked)
       {
        tl.days.push(3);
       }
       if(timelimits[i].querySelectorAll('input[name="thu"]')[0].checked)
       {
        tl.days.push(4);
       }
       if(timelimits[i].querySelectorAll('input[name="fri"]')[0].checked)
       {
        tl.days.push(5);
       }
       if(timelimits[i].querySelectorAll('input[name="sat"]')[0].checked)
       {
        tl.days.push(6);
       }
       
       tl.from = timelimits[i].querySelectorAll('input[name="starttime"]')[0].value;
       tl.to = timelimits[i].querySelectorAll('input[name="endtime"]')[0].value;
      data.timelimits.push(tl);
   }
   
   const options = {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(data)
  };
  fetch('/durabunny.lua', options)
  let saved = document.getElementById('saved');
  saved.style.display = "inline";
  return true;
}
</script>


<div id="info">
<h1>Energy Management Configuration</h1>
</div>
<div class="formLayoutfull">
  <form action="/durabunny.lua" method="post" id="duraform">
  <h3>Inhibit Output:</h3>
    <label for="output">Inhibit Output: </label>  
    <select id="output" name="outputselect">
      {% for _,dev in ipairs(deviceinfo) do %}
      <optgroup label="{{dev.name}} - {{dev.serial}}">
        {% for _,oport in ipairs(dev.outputs) do %}
        <option value="{{dev.serial}}:{{oport}}" 
                {% if (cfg.output.label == oport) and (cfg.output.deviceid == dev.serial) then %} 
                 selected 
                {% end %}>{{oport}}</option>
        {% end %}
       </optgroup> 
      {% end %} 
      </select>
    <h3>Inhibit Release Triggers:</h3>
    <div style="border: 1px solid black; padding: 5px;">
    <ul id="triggers" style="list-style-type: none;" name="triggers">
      {% for _,trigger in ipairs(cfg.triggers) do %} 
      {% if trigger.type == "analog" then %}
      <li>
           <select name="analog" id="analogid">
            {% for _,dev in ipairs(deviceinfo) do %}
            <optgroup label="{{dev.name}} - {{dev.serial}}">
              {% for _,aport in ipairs(dev.analogs) do %}
              <option value="{{dev.serial}}:{{aport}}"
                      {% if (trigger.label == aport) and (trigger.deviceid == dev.serial) then %} 
                        selected 
                      {% end %}>{{aport}}</option>
              {% end %}
            </optgroup> 
            {% end %}
           </select>
           <select name="operation" id="ltgtid">
              <option value="lt" {% if trigger.operation == "lt" then %} selected {% end %}>Less Than</option>
              <option value="gt" {% if trigger.operation == "gt" then %} selected {% end %}>Greater Than</option>
           </select>
           <input type="number" name="value" id="valueid" step="any" placeholder="0.0" value="{{trigger.value}}">
           <a style="cursor:pointer; color:blue;" onclick="removeTrigger(this)">
              <img src="images/trash.png" alt="Delete" title="Delete"/>
           </a>
       </li>
       {% end %}
       {% end %}
    </ul>
    <button id="addtrigger" type="button" onclick="addTrigger()">Add Trigger</button>
  </div>
  <h3>Time Limits:</h3>
  <div style="border: 1px solid black; padding: 5px;">
    <ul id="timelimits" style="list-style-type: none;" name="timelimits">
      {% for _,tl in ipairs(cfg.timelimits) do %}
      <li>
        <select name="mustrun">
            <option value="false" {% if tl.mustrun == "false" then %}selected{% end %}>Must Not Run</option>
            <option value="true" {% if tl.mustrun == "true" then %}selected{% end %}>Must Run</option>
        </select>
        Su<input type="checkbox" id="sun0" name="sun" {% if helpers.isInArray(tl.days,0) == true then %} checked {% end %}>
        Mo<input type="checkbox" id="mon0" name="mon" {% if helpers.isInArray(tl.days,1) == true then %} checked {% end %}>
        Tu<input type="checkbox" id="tue0" name="tue" {% if helpers.isInArray(tl.days,2) == true then %} checked {% end %}>
        We<input type="checkbox" id="wed0" name="wed" {% if helpers.isInArray(tl.days,3) == true then %} checked {% end %}>
        Th<input type="checkbox" id="thu0" name="thu" {% if helpers.isInArray(tl.days,4) == true then %} checked {% end %}>
        Fr<input type="checkbox" id="fri0" name="fri" {% if helpers.isInArray(tl.days,5) == true then %} checked {% end %}>
        Sa<input type="checkbox" id="sat0" name="sat" {% if helpers.isInArray(tl.days,6) == true then %} checked {% end %}>
        From <input type="time"  name="starttime" value="{{tl.from}}">
        To <input type="time"  name="endtime" value="{{tl.to}}">
        <a style="cursor:pointer; color:blue;" onclick="removeTimeLimit(this)">
          <img src="images/trash.png" alt="Delete" title="Delete"/>
       </a>
      </li>
      {% end %}
    </ul>
    <button id="addtimelimit" type="button" onclick="addTimeLimit()">Add Time Limit</button>
  </div>
    <br>
    <br>
    <div id="saved" style="display: none;">
    <br><b><img src="images/ok.png"/> Changes saved, but may take a few seconds to take effect.</b><br><br>
    </div>
    <button type="submit" name="submitButton" value="Save and Apply" {{buttonControl}}>Save and Apply</button>
    </form>
</div>
<script>
let duraForm = document.getElementById('duraform');

console.log("New location");

duraForm.addEventListener("submit", (e) => {
  //Prevent browser default behavior
  e.preventDefault();
  console.log("In the event Listener"); 
  // More code here in the next step
  submitData();
  console.log("Data Sent"); 

})
 
</script>