function http(method, remote, callback, body) {
   var xmlhttp = new XMLHttpRequest();
   xmlhttp.onreadystatechange = function() {
      if (xmlhttp.readyState == XMLHttpRequest.DONE) {
         callback(xmlhttp.responseText, xmlhttp.status)
      }
   };
   xmlhttp.open(method, remote, true);
   if (typeof body == "undefined") {
      body = null
   }
   xmlhttp.send(body);
}

function upserts() {
   function cb(body, status) {
      console.log(status, body)
   }
   http("POST", "/upserts", cb, jsonifyForm("upserts"))
}

function jsonifyForm(id) {
   var form = document.getElementById(id)
   var entries = new FormData(form).entries();
   var json = Object.assign(...Array.from(entries, ([x,y]) => ({[x]:y})));
   var s = JSON.stringify(json)
   return s
}

function init() {
   function cb(body, status) {
      var jobs = JSON.parse(body)
      jobs.forEach(function(job) {
         var s = format(job)
         inject(s)
         console.log("job=", job)
         console.log("s=", s)
      })
   }
   function format(job) {
      return `<tr><td><details>
         <summary name="${job.id}">(${job.last.status}) ${job.title}</summary>
         <table>
            <tr>
               <td><code>${job.cron}</code></td>
               <td><code>${job.language}</code></td>
               <td><code>${job.script}</code></td>
            </tr>
            <tr>
               <td><code>${job.last.run}</code></td>
               <td><code>${job.last.runtime}</code></td>
               <td><code>${job.last.output}</code></td>
            </tr>
         </table>
      </details></td></tr>`
   }
   function inject(s) {
      var table = document.getElementById("jobs").getElementsByTagName("tbody")[0]
      table.innerHTML += s
   }
   http("GET", "/list", cb, null)
}

init()
