var gateway = `ws://${window.location.hostname}/ws`;
var websocket;

window.addEventListener("load", onLoad);

function initWebSocket() {
  console.log("Trying to open a WebSocket connection...");
  websocket = new WebSocket(gateway);
  websocket.onopen = onOpen;
  websocket.onclose = onClose;
  websocket.onmessage = onMessage; // <-- add this line
}

function initButtons() {
  document
    .getElementById("btn-ws-stop")
    .addEventListener("click", livedebug_stop);
  document
    .getElementById("btn-ws-start")
    .addEventListener("click", livedebug_start);
}

function onOpen(event) {
  console.log("Connection opened");
}

function onClose(event) {
  console.log("Connection closed");
  setTimeout(initWebSocket, 2000);
}

function onMessage(event) {
  var livedebug_out = document.getElementById("livedebug-out");
  var textarea_heigth = livedebug_out.scrollHeight;
  livedebug_out.value += event.data;
  livedebug_out.scrollTop = livedebug_out.scrollHeight;
  do_resize(livedebug_out);
}

function onLoad(event) {
  initWebSocket();
  initButtons();
}

function livedebug_start() {
  websocket.send("start");
}

function livedebug_stop() {
  websocket.send("stop");
}

function do_resize(textbox) {
  var maxrows = 15;
  var minrows = 3;
  var txt = textbox.value;
  var cols = textbox.cols;

  var arraytxt = txt.split("\n");
  var rows = arraytxt.length;

  for (i = 0; i < arraytxt.length; i++)
    rows += parseInt(arraytxt[i].length / cols);

  if (rows > maxrows) textbox.rows = maxrows;
  else if (rows < minrows) textbox.rows = minrows;
  else textbox.rows = rows;
}

function notifyMe() {
  if (!("Notification" in window)) {
    alert("This browser does not support desktop notification");
  } else if (Notification.permission === "granted") {
    const notification = new Notification("Hi there!");
    // …
  } else if (Notification.permission !== "denied") {
    Notification.requestPermission().then((permission) => {
      if (permission === "granted") {
        const notification = new Notification("Hi there!");
        // …
      }
    });
  }
}
