import mysql.connector.locales.eng
import mysql.connector
import os
import Controller.ssh_tunnel as ssh_tunnel

filename = os.path.basename(__file__)

def database(query,name,user):
    # server.start()
    print(f"{filename}-SSH Server start Port:{ssh_tunnel.server_port()}")

    mydb = mysql.connector.connect(
        host="127.0.0.1",
        port=ssh_tunnel.server_port(),
        user="root",
        password="N53yBCswuawzBzS445VNAhWVMs3N59Gb9szEsrzXRBzarDqpdETpQeyt5v5CGe",
        database="" + name,
        auth_plugin='mysql_native_password',
    )
    mydb.connect()
    print(f"{filename}-SQL Server Connect")
    print(f"{filename}-{query}")
    cursor = mydb.cursor()
    if "SELECT" in query:
        if user:
            cursor.execute(query, user)
            return cursor.fetchone()
        else:
            cursor.execute(query, user)
            print(f"{filename}- Inside SELECT ALL")
            return cursor.fetchall()
    if "SHOW" in query:
        cursor.execute(query)
        return cursor.fetchall()
    if "INSERT" in query:
        cursor.execute(query,user)
        mydb.commit()
    if "UPDATE" in query:
        cursor.execute(query,user)
        mydb.commit()
    mydb.close()
    # server.stop()
def get_ip(query):
    print(f"{filename}-GetIP")
    user = ""
    name = ""
    return database(query, name, user)
def get_database():
    name = ""
    user = ""
    query = 'SHOW DATABASES'
    return database(query,name,user)
def create_database(query,name):
    try:
        user = ""
        database(query,name,user)
    except Exception as e:
        print(f"{filename}-Ein Fehler ist aufgetreten:", str(e))
def add_user(query,name,user):
    try:
        database(query, name, user)
        return print(f"{filename}-User Added")
    except Exception as e:
        print(f"{filename}-Ein Fehler ist aufgetreten:", str(e))

def get_user(query,name,user):
    return database(query,name,user)

def get_cpu(query,name,cpu):
    return database(query,name,cpu)

def update_cpu(query,name):
    return database(query,name,"")