import subprocess
import csv
from datetime import datetime
from Controller import mysql_connect


def adcontroller (ip,name):
    command = ["powershell", "-Command",
               "Get-ADUser -Filter * -Properties * | Export-Csv -NoTypeInformation -Encoding UTF8 -Path 'users.csv'"]
    subprocess.run(command)
    # CSV-Datei einlesen und Feldnamen auslesen
    with open("users.csv", "r", encoding='utf-8-sig') as file:
        reader = csv.DictReader(file)
        fieldnames = reader.fieldnames

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

    # Daten aus der CSV-Datei in die Tabelle einfügen
    with open("users.csv", "r", encoding='utf-8-sig') as file:
        reader = csv.reader(file)
        next(reader)  # Überspringe die erste Zeile (Feldnamen)
        for row in reader:
            row = [cell if cell.strip() else "-" for cell in row]
            unix_time = int(datetime.now().timestamp())
            print(unix_time)
            row = [unix_time] + row
            insert_query = f"INSERT INTO `{table_name}` (importdate, `{'`, `'.join(fieldnames)}`) VALUES (%s, {', '.join(['%s'] * len(fieldnames))})"
            mysql_connect.add_user(insert_query, name, row)

    # Datenbankverbindung schließen

    command = ["powershell", "-Command",
               "Get-ADGroupMember -Identity G-RDP-User | Export-Csv -NoTypeInformation -Encoding UTF8 -Path 'group.csv'"]
    subprocess.run(command)

    # CSV-Datei einlesen und Feldnamen auslesen
    with open("group.csv", "r", encoding='utf-8-sig') as file:
        reader = csv.DictReader(file)
        fieldnames = reader.fieldnames
    table_name = "Active-Directory-RDS-User"
    create_table_query = f"CREATE TABLE IF NOT EXISTS `{table_name}` (id INT AUTO_INCREMENT PRIMARY KEY, importdate BIGINT(11), "
    for field in fieldnames:
        create_table_query += f"`{field}` TEXT, "
    create_table_query = create_table_query.rstrip(", ") + ")"
    mysql_connect.create_database(create_table_query, name)

    # Daten aus der CSV-Datei in die Tabelle aktualisieren oder einfügen
    with open("group.csv", "r", encoding='utf-8-sig') as file:
        reader = csv.DictReader(file)
        for row in reader:
            sam_account_name = row["SamAccountName"]

            # Abfrage, um die ID für den Benutzernamen zu erhalten
            query_id = f"SELECT id FROM `{table_name}` WHERE SamAccountName = %s"
            result = mysql_connect.get_user(query_id, name, (sam_account_name,))

            if result:
                user_id = result[0]
                print(user_id)
                update_query = f"UPDATE `{table_name}` SET "
                for field in fieldnames:
                    if field != "SamAccountName":  # Spaltenname nicht in das UPDATE einbeziehen
                        update_query += f"`{field}` = %s, "
                update_query = update_query.rstrip(", ")
                update_query += ", `importdate` = %s"  # Importdate als Unix-Timestamp aktualisieren
                update_query += " WHERE id = %s"

                row_data = [row[field] for field in fieldnames if field != "SamAccountName"]
                unix_time = int(datetime.now().timestamp())
                row_data = row_data + [unix_time]
                row_data.append(user_id)
                print(row_data)
                mysql_connect.add_user(update_query, name, row_data)
            else:
                insert_query = f"INSERT INTO `{table_name}` ("
                insert_query += ", ".join(fieldnames)  # Spaltennamen in die INSERT-Abfrage einbeziehen
                insert_query += ", `importdate`) VALUES ("
                insert_query += ", ".join(["%s"] * (len(fieldnames) + 1))  # Zusätzliches %s für importdate
                insert_query += ")"
                row_data = [row[field] for field in fieldnames]
                unix_time = int(datetime.now().timestamp())
                row_data = row_data + [unix_time]
                print(row_data)
                mysql_connect.add_user(insert_query, name, row_data)
                # connection.commit()
