<!DOCTYPE html>
<html lang="de">
<head>
    <script>
        let termdiv;
        let terminput;
        let timer;
        let timertext;
        const COMMAND = "command";


        function sendcommand(contentlist) {
            fetch("/termapi",{
                method:"POST",
                body: JSON.stringify({"content":contentlist}),
                headers: {"Content-type":"application/json; charset=UTF-8"}
            }).then(getterm());
        }
        function sendtermcommand() {
            sendcommand([COMMAND,
                            `terminal-command`,
                            terminput.value]
            );
            terminput.value = "";
            
        }

        function getterm() {
            let tmpterm = "";
            fetch("/term", { method: "GET" })
                .then(response => response.json())
                .then(termarray => {
                    console.log(termarray);
                    for (let line of termarray) {
                        tmpterm += `${line}<br>`;
                    }
                    termdiv.innerHTML = tmpterm;
                })
                .catch(termdiv.innerHTML = 'Fehler beim Abrufen der Daten');
        }
        function getterminterval() {
            timer -= 1
            timertext.innerHTML = `Reload in ${timer} Seconds`
            if (timer == 0) {
                getterm()
                timer = 5
            }
        }


        function initstuff() {
            timer = 5
            timertext = document.getElementById("timer")
            termdiv = document.getElementById("terminaltext");
            terminput = document.getElementById("terminalinput");
            getterm();
            setInterval(getterminterval,1000)
        }

        window.onload = initstuff;
    </script>
    <link rel="stylesheet" href="{{ url_for('static', filename='navbar.css') }}">
    <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
    <link rel="shortcut icon" href="{{ url_for('static', filename='favicon.ico') }}">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Terradash</title>
</head>
<body>
    {{ navbar | safe }}
    <div class="main" style="width: 100%;height: 100vh;">
        <h1>Terminal</h1>
        <div>
            <p id="timer">Reload in _ Seconds</p>
            <div id="terminal">
                <div id="terminaltext"></div>
                <input id="terminalinput" type="text">
                <button
                style="margin-top: 15px;"
                class="button"
                onclick="sendtermcommand();
                terminput.value = ``">send</button>
            </div>
        </div>
    </div> 
</body>
</html>
