#!/usr/bi/python3
from flask import *
from main import launchserver
import libtmux

app = Flask("Terradash")

server = libtmux.Server()
session = None


def initialize_tmux_session():
    global session
    # Versuche, die bestehende Session zu finden
    if server.has_session("terradash"):
        session = server.sessions.get(session_name="terradash")


def get_term():
    lpane = getlpane()
    return lpane.capture_pane(), lpane.pane_current_command


def getlpane() -> libtmux.Pane:
    print(session)
    if not session:
        print(session)
        return ["No Terminal is running"]
    window = session.active_window
    lpane = window.panes[0]
    return lpane


@app.route("/term", methods=["GET", "POST"])
def get_terminal_output():
    if request.method == "POST":
        data = request.get_json()#json.loads(request.data.decode())
        print(data,type(data))
        content = data["content"]
        if content[0] == "command":
            if content[1] == "start" and getlpane().pane_current_command == "bash":
                launchserver(getlpane())

            elif content[1] == "stop" and getlpane().pane_current_command == "mono":
                getlpane().send_keys("\nexit")
            elif content[1] == "terminal-command" and getlpane().pane_current_command == "mono":
                getlpane().send_keys(content[2])

            return ["sucessful"]
    elif request.method == "GET":
        term = get_term()
        if term[1] == "mono":
            return term[0]
        else:
            return ["Server not running."]


@app.route("/")
def root():
    return render_template("index.html")


if __name__ == "__main__":
    initialize_tmux_session()
    app.run(host="0.0.0.0", debug=True)
