#!/usr/bi/python3
import flask
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("/termapi", 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 flask.redirect("/dash")

@app.errorhandler(404)
def e404(e):
    return render_template("404.html")


## sites

@app.route("/dash")
def dash():
    navbar = render_template("navbar.html")
    return render_template("sites/dash.html",navbar=navbar)

@app.route("/config")
def configs():
    navbar = render_template("navbar.html")
    return render_template("sites/config.html",navbar=navbar)

@app.route("/worlds")
def worlds():
    navbar = render_template("navbar.html")
    return render_template("sites/worlds.html",navbar=navbar)

@app.route("/log")
def logs():
    navbar = render_template("navbar.html")
    return render_template("sites/log.html",navbar=navbar)

@app.route("/terminal")
def term():
    navbar = render_template("navbar.html")
    return render_template("sites/terminal.html",navbar=navbar)


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