/* clang-format off */

#ifdef ENABLE_FEATURE_WEB_CONSOLE

static const char js_csapp[] PROGMEM = R"=====(function g(i) { return document.getElementById(i) };
var xhttp, updateTime, reqTime, reqFin;
var msgList = document.getElementById('msgs');

g('cmdInput').addEventListener("keyup", function(event) {
    event.preventDefault();
    if (event.keyCode === 13) {
		sendCmd();
    }
});

function sendCmd() {
  var form = g('cmdForm');
  msgList.innerHTML += 'Sent: ' + g('cmdInput').value + '\n';
  g('cmd').value=g('cmdInput').value;
  g('cmdInput').value='';
  g('cmdInput').value = '';
  msgList.scrollTop = msgList.scrollHeight;
  return transmit(form);
}

var lastMsgIndex=0;

function transmit(f) {
  if (!xhttp) { 
    reqTime = 0;
    reqFin = false;
    xhttp = new XMLHttpRequest();
    xhttp.timeout = 1000;
    xhttp.overrideMimeType("text/plain");
    xhttp.open('POST', 'webcsapi');
    xhttp.send(f ? (new FormData(f)) : '');
    xhttp.onreadystatechange = function () {
      if (xhttp.readyState === XMLHttpRequest.DONE && xhttp.status === 200) {
        var data = xhttp.responseText.split("\n");
		    for(i=0; i < data.length; i++) {
		      var numEnd = data[i].indexOf("}");
		      var num = parseInt(data[i].substring(1, numEnd));
		      var msg = data[i].substring(numEnd+1);
		      if(num > lastMsgIndex || lastMsgIndex == 0) {
            msgList.innerHTML += msg;
			      msgList.scrollTop = msgList.scrollHeight;
			      lastMsgIndex = num;
		      }
		    }
		
        xhttp = null;
        updateTime = 0;
        reqFin = true;
        }
      else {
        if(!reqFin && reqTime > 10) {
          xhttp = null;
          reqFin = true;
        }
      }
    }
  }
  return false;
}

transmit();
setInterval(transmit, 2000);

)====="; // js_csapp

static const char html_console_body[] PROGMEM = R"=====(
<p><b>Console</b></p>
<table style='width:100%'>
<tr><td style='width:800px;'><textarea id="msgs" style="width:100%;min-height:400px;resize:both;"></textarea></td></tr>
<tr><td><input id='cmdInput' type='text'></td></tr>
<tr><td><button type='submit' id='btnSend' onclick='sendCmd();'>Send</button></td></tr>
<tr><td><form action='.' method='get'><button class='bgrey'>Close</button></form></td></tr>
</table>

<form id='cmdForm'>
<input type='hidden' name='cmd' id='cmd'>
</form>

<script src="csapp.js"></script>


)====="; // html_console_body

#endif