{% block sisalto %}
  <div style="width: 100%; height: calc(100% - 50px);" id="xterm"></div>
{% endblock sisalto %}

{% block skriptit %}
  <script src="https://unpkg.com/xterm@4.5.0/lib/xterm.js"></script>
  <script src="https://unpkg.com/xterm-addon-fit@0.3.0/lib/xterm-addon-fit.js"></script>
  <script src="https://unpkg.com/xterm-addon-web-links@0.3.0/lib/xterm-addon-web-links.js"></script>
  <script src="https://unpkg.com/xterm-addon-search@0.6.0/lib/xterm-addon-search.js"></script>

  <script>
    // vrt. https://github.com/Om3rr/pyxtermjs/master/pyxtermjs/index.html
    term = null;
    websocket = null;
    fit = null;

    function fitToScreen(){
      if (websocket && term && fit) {
        fit.fit();
        websocket.send(JSON.stringify({cols: term.cols, rows: term.rows}))
      }
    }
    function debounce(func, wait_ms) {
      let timeout
      return function(...args) {
        const context = this
        clearTimeout(timeout)
        timeout = setTimeout(function () { func.apply(context, args); }, wait_ms)
      }
    }
    window.onresize = debounce(fitToScreen, 50);

    function avaa_xterm(avattu) {
      if (term)
        term.dispose();
      if (websocket)
        websocket.close();

      term = new Terminal({{ view.xterm|safe }});
      fit = new FitAddon.FitAddon();
      term.loadAddon(fit);
      term.loadAddon(new WebLinksAddon.WebLinksAddon());
      term.loadAddon(new SearchAddon.SearchAddon());
      term.open(document.getElementById('xterm'));
      fit.fit()
      term.onKey(function(e) {
        websocket.send(new Blob([e.key]));
      });

      websocket = new WebSocket(
        "{{ request.websocket }}{{ request.path }}"
      );
      websocket.onopen = function () {
        if (avattu)
          avattu(websocket);
        fitToScreen();
      };
      websocket.onmessage = function (e) {
        term.write(e.data)
      };
    };
  </script>
{% endblock skriptit %}

{% block tyyli %}
  <link rel="stylesheet" href="https://unpkg.com/xterm@4.5.0/css/xterm.css" />
{% endblock tyyli %}
