{% extends "app.html" %}

{% block sidebar %}

{% include "sidebar_channels.html" %}

{% endblock %}

{% block main %}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/xterm/css/xterm.css">
    <script src="https://cdn.jsdelivr.net/npm/xterm/lib/xterm.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/xterm-addon-fit/lib/xterm-addon-fit.js"></script>
    <style>
       #terminal { margin-right: 5%; width: 90%; height: 90%; overflow-y: none; }
       #terminal::-webkit-scrollbar { display: none; }
    </style>

  <div class="container" id="terminal"></div>

    <script>
        const term = new Terminal({ cursorBlink: true });
        const fitAddon = new FitAddon.FitAddon();
        term.loadAddon(fitAddon);
        term.open(document.getElementById("terminal"));
        fitAddon.fit();

        window.addEventListener("resize", () => fitAddon.fit());
        
        const schema = window.location.protocol === "https:" ? "wss" : "ws";
        const hostname = window.location.host;
        const url = `${schema}://${hostname}/terminal.ws`;

        const socket = new WebSocket(url);
        socket.binaryType = "arraybuffer";  // Support binary data

        socket.onopen = () => { 
            fitAddon.fit();
            term.write("\x0C");
            
        }

        socket.onmessage = (event) => {
            const data = new Uint8Array(event.data);
            term.write(new TextDecoder().decode(data));
        };

        term.onData(data => socket.send(new TextEncoder().encode(data)));

        socket.onclose = () => term.write("\r\n\x1b[31mConnection closed\x1b[0m\r\n");
    </script>



{% endblock main %}
