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

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,
    )
    resultstring = result.stdout.strip()
    resultstring = re.compile(r'\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])').sub('', resultstring)
    messages = resultstring.split(': ')
    print(messages)
    messagelist = messages[0].split(" ")
    usercount = int(messagelist[2])
    maxcount = int(messagelist[7])
    userlist = None
    usercombolist = None

    if usercount > 0:
        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")
