import subprocess
from datetime import datetime
from Controller import mysql_connect


def rds (ip,name):
    powershell_command = "quser | Select-String -Pattern 'Aktiv'"
    result = subprocess.run(["powershell", "-Command", powershell_command], capture_output=True, text=True)
    fieldname = ["Benutzername","Anmeldezeit","Anmeldedatum"]
    # Die Ausgabe des Befehls aufteilen und die Benutzernamen und Anmeldezeiten extrahieren
    output_lines = result.stdout.strip().split('\n')[1:]
    logged_in_users = []

    # Tabelle erstellen, falls sie noch nicht existiert
    table_name = "RDS-Online-User"
    create_table_query = f"CREATE TABLE IF NOT EXISTS `{table_name}` (id INT AUTO_INCREMENT PRIMARY KEY, importdate INT(11), "
    for field in fieldname:
        create_table_query += f"`{field}` TEXT, "
    create_table_query = create_table_query.rstrip(", ") + ")"
    create_table_query += " ROW_FORMAT=DYNAMIC"
    user = ""
    mysql_connect.create_database(create_table_query, name)

    for line in output_lines:
        parts = line.split()
        username = parts[0].replace(">","")
        login_time = parts[5]
        login_date = parts[6]
        logged_in_users.append((username,login_date, login_time))

    for user in logged_in_users:
        user = [cell if cell.strip() else "-" for cell in user]
        unix_time = int(datetime.now().timestamp())
        user = [unix_time] + user
        insert_query = f"INSERT INTO `{table_name}` (importdate, `{'`, `'.join(fieldname)}`) VALUES (%s, {', '.join(['%s'] * len(fieldname))})"
        mysql_connect.add_user(insert_query, name, user)