import subprocess
from flask import Flask, render_template
from dotenv import load_dotenv
import os

load_dotenv()
app = Flask(__name__)


@app.route("/")
def home():
    result = subprocess.run(
        [
            os.environ["MCRCON"],
            "-H",
            os.environ["HOST"],
            "-p",
            os.environ["PASSWORD"],
            "list uuids",
        ],
        capture_output=True,
        text=True,
    )
    messages = result.stdout.strip().split(": ")
    messagelist = messages[0].split(" ")
    usercount = messagelist[2]
    maxcount = messagelist[7]
    userlist = None
    usercombolist = None

    if len(messages) > 1:
        userlist = messages[1].split(", ")

        usercombolist = []
        for user in userlist:
            username = user[: user.find(" ")]
            uuid = user[user.find("(") + 1 : -1]
            usercombolist.append((username, uuid))

    return render_template(
        "home.html",
        usercount=usercount,
        maxcount=maxcount,
        userlist=usercombolist,
    )


if __name__ == "__main__":
    app.run(host="0.0.0.0")
