import psycopg2
from datetime import datetime, timedelta
from Controller import mysql_connect

def tickets(ip,name):
    # Verbindungsinformationen zur PostgreSQL-Datenbank
    db_host = "172.17.1.5"
    db_name = "zammad_production"
    db_user = "zammad"
    db_password = "zammad"

    table_name = "Tickets"

     # Verbindung zur Datenbank herstellen
    connection = psycopg2.connect(
         host=db_host,
         database=db_name,
         user=db_user,
         password=db_password
    )
    ## Abfrage der Daten mit SL / ZL
    cursor = connection.cursor()
    query = "SELECT tickets.*, tag_items.name AS SLA FROM tickets LEFT JOIN tags ON tickets.id = tags.o_id LEFT JOIN tag_items ON tags.tag_item_id = tag_items.id;"
    cursor.execute(query)

    ## Header auslesen
    headers = [desc[0] for desc in cursor.description]

    ## Orga Auslesen
    group = f"SELECT id FROM groups WHERE name = '{name.replace('ae','ä').replace('ue','ü').replace('oe','ö').replace('-',' ')}'"
    cursor.execute(group)
    query = f"SELECT tickets.*, tag_items.name AS SLA FROM tickets LEFT JOIN tags ON tickets.id = tags.o_id LEFT JOIN tag_items ON tags.tag_item_id = tag_items.id WHERE group_id = {cursor.fetchone()[0]}"
    cursor.execute(query)
    results = cursor.fetchall()

    column_type = f"SELECT column_name, data_type FROM information_schema.columns WHERE table_name = 'tickets' order by column_name ASC;"
    cursor.execute(column_type)
    column_type = cursor.fetchall()

    columns = ""
    ## Cretae Tabelle with column_type
    create_table_query = f"CREATE TABLE IF NOT EXISTS `{table_name}` (importdate BIGINT(11), "
    for i in column_type:
        columns += f"{i[0]},"
        if i[1] == "timestamp without time zone":
            create_table_query += f"`{i[0]}` DATETIME, "
        elif i[1] == "character varying":
            create_table_query += f"`{i[0]}` TEXT, "
        else:
            create_table_query += f"`{i[0]}` {i[1]}, "
    create_table_query = create_table_query.rstrip(",") + "sla TEXT)"
    mysql_connect.create_database(create_table_query, name)

    for row in results:
        unix_time = int(datetime.now().timestamp())
        id = mysql_connect.get_user(f"SELECT id FROM `{table_name}` where id = '%s'", name,(row[0],))
        given_date = datetime.strptime(str(row[36]), "%Y-%m-%d %H:%M:%S.%f")
        yesterday = datetime.now() - timedelta(days=1)
        if id is None:
            insert_query = f"INSERT INTO `{table_name}` (importdate, `{'`, `'.join(headers)}`) VALUES (%s, {', '.join(['%s'] * len(headers))})"
            mysql_connect.add_user(insert_query, name, (unix_time,) + row)
        else:
            if given_date > yesterday:
                update_query = f"UPDATE `{table_name}` SET "
                for field in headers:
                    update_query += f" `{field}` = %s, "
                update_query = update_query.rstrip(", ")
                update_query += f" WHERE id = {row[0]}"
                mysql_connect.add_user(update_query,name, row)