import mysql.connector
import subprocess
import csv
from datetime import datetime

def adcontroller (ip,name):
    connection = mysql.connector.connect(
        host="172.17.1.21",
        user="root",
        password="N53yBCswuawzBzS445VNAhWVMs3N59Gb9szEsrzXRBzarDqpdETpQeyt5v5CGe",
        database="" + name
    )
    command = ["powershell", "-Command",
               "Get-ADUser -Filter * -Properties * | Export-Csv -NoTypeInformation -Encoding UTF8 -Path 'users.csv'"]
    subprocess.run(command)

    cursor = connection.cursor()

    # 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(", ") + ")"
    cursor.execute(create_table_query)
    connection.commit()

    # 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())
            row = [unix_time] + row
            insert_query = f"INSERT INTO `{table_name}` (importdate, `{'`, `'.join(fieldnames)}`) VALUES (%s, {', '.join(['%s'] * len(fieldnames))})"
            cursor.execute(insert_query, row)
            connection.commit()

    # Datenbankverbindung schließen

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

    cursor = connection.cursor()

    # 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(", ") + ")"
    cursor.execute(create_table_query)
    connection.commit()

    # 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"
            cursor.execute(query_id, (sam_account_name,))
            result = cursor.fetchone()

            if result:
                user_id = result[0]
                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"]
                row_data.append(int(datetime.now().timestamp()))  # Aktuelle Zeit als Unix-Timestamp
                row_data.append(user_id)
                cursor.execute(update_query, row_data)
                connection.commit()
            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]
                row_data.append(int(datetime.now().timestamp()))  # Aktuelle Zeit als Unix-Timestamp
                cursor.execute(insert_query, row_data)
                connection.commit()

    # MySQL-Verbindung schließen
    connection.close()