import requests
from datetime import datetime
from Controller import mysql_connect


def smtp(ip,name,mailcow_token):

    mailcow_url = f"http://{ip}/api/v1"
    mailcow_token = f"{mailcow_token}"

    response = requests.get(f"{mailcow_url}/get/mailbox/all", headers={"X-API-Key": mailcow_token})

    json_data = response.json()

    for entry in json_data:
        frame = {'frame':'s',
                 'value':'10'}
        for column, frame in frame.items():
            if column not in entry:
                entry[column] = frame

    ## löscht das Feld attributes
    for entry in json_data:
        attributes = entry.pop('attributes', None)
        if attributes:
            entry.update(attributes)

    ## löscht das Feld attributes
    for entry in json_data:
        rl = entry.pop('rl', None)
        if rl:
            entry.update(rl)
            print(entry)

    ## Fühlt alle leeren Felder mit "-" auf
    for entry in json_data:
        for key, value in entry.items():
            if value is None or value == "":
                entry[key] = "-"
    fields = list(json_data[0].keys())


    table_name = "SMTP-User"
    create_table_query = f"CREATE TABLE IF NOT EXISTS `{table_name}` (id INT AUTO_INCREMENT PRIMARY KEY,importdate BIGINT(11), "
    for field in fields:
        if field == 'id':
            field = 'User-ID'
        create_table_query += f"`{field}` TEXT, "
    create_table_query = create_table_query.rstrip(", ") + ")"
    mysql_connect.create_database(create_table_query, name)

    print(len(fields))
    columns = ", ".join(json_data[0].keys())
    values_placeholder = ", ".join(["%s"] * len(fields))
    unix_time = int(datetime.now().timestamp())
    print(unix_time)

   #SQL-Query zusammenstellen
    insert_query = f"INSERT INTO `{table_name}` (importdate,{columns}) VALUES (%s,{values_placeholder})"

    # Durchlaufen der JSON-Daten und Einfügen in die Datenbank
    for entry in json_data:
        values = tuple(
            cell if isinstance(cell, int) else cell.strip() if cell.strip() else "-" for cell in entry.values())
        mysql_connect.add_user(insert_query, name, (unix_time,) + values)
