import mysql.connector.locales.eng
import mysql.connector
from sshtunnel import SSHTunnelForwarder
import os

def ping(host):
    # Führe den Ping-Befehl aus und erfasse die Ausgabe
    result = os.system("ping -c 1 " + host)
    if result == 0:
        hostname = "172.17.1.21", 22
    else:
        hostname = "forward.stines.de", 2223
    return hostname

server = SSHTunnelForwarder(
        ("forward.stines.de", 2223),
        ssh_username="root",
        ssh_password="adm.3dfx12",
        remote_bind_address=('127.0.0.1', 3306)
)
def database(query,name,user):
    server.start()
    mydb = mysql.connector.connect(
        host="127.0.0.1",
        port=server.local_bind_port,
        user="root",
        password="N53yBCswuawzBzS445VNAhWVMs3N59Gb9szEsrzXRBzarDqpdETpQeyt5v5CGe",
        database="" + name,
        auth_plugin='mysql_native_password',
    )
    mydb.connect()
    cursor = mydb.cursor()
    if user:
        if "SELECT" in query:
            cursor.execute(query,user)
            return cursor.fetchone()
        else:
            cursor.execute(query,user)
            mydb.commit()
    else:
        cursor.execute(query)
    if "SELECT" in query:
        return cursor.fetchall()
    if "SHOW" in query:
        return cursor.fetchall()
    mydb.close()
    server.stop()
def get_ip(query):
    print("GetIP")
    user = ""
    name = ""
    return database(query, name,user)
def get_database():
    name = ""
    user = ""
    query = 'SHOW DATABASES'
    print(database(query,name,user))
    return database(query,name,user)
def create_database(query,name):
    try:
        user = ""
        database(query,name,user)
        return ("Database Created")
    except Exception as e:
        print("Ein Fehler ist aufgetreten:", str(e))
def add_user(query,name,user):
        return database(query,name,user)

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,cpu):
    return database(query,name,cpu)