import socket
from Controller import adcontroller_export, exchange_export, rds_export, smtp_export, zammad, system_info
import Controller.mysql_connect as mysql_connect
import random
import subprocess
import socket

def get_local_ip():
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(("8.8.8.8", 80))
        local_ip = s.getsockname()[0]
        s.close()
        print(local_ip)
        return local_ip
    except Exception as e:
        print(f"Fehler beim Abrufen der lokalen IP-Adresse: {e}")
        return None

def system_info_get(ip,name):
    system_info.set_system_info(name,ip)

def adcontroller(ip,name):
    adcontroller_export.adcontroller(ip, name)

def exchange(ip,name):
    exchange_export.exchange(ip, name)

def smtp(ip,name,token):
    smtp_export.smtp(ip, name, token)

def rds(ip, name):
    rds_export.rds(ip, name)

def cms(ip, servername):
    ## Import User als RAW
    print("" + ip + servername)

def mstore(ip, servername):
    ## Import User(last Check) als RAW
    print("" + ip + servername)

def cloud(ip,servername):
    ## Import User(space) als RAW
    print("" + ip + servername)

def vpn(ip,servername):
    ## Import Online Time als RAW
    print("" + ip + servername)

def nginx(ip,servername):
    ## Import Letsencrypt Time als RAW
    print("" + ip + servername)

def tickets(ip,name):
    zammad.tickets(ip,name)

def data(ip,servername):
    ## Import Space Used als RAW
    print("" + ip + servername)

def omada(ip,servername):
    ## Import Access als RAW
    print("" + ip + servername)

def matomo(ip,servername):
    ## Import Statics als RAW
    print("" + ip + servername)

def gucamole(ip,servername):
    ## Import User + Maschinen als RAW
    print("" + ip + servername)

def create_windows_task(task_name, command, schedule):
    try:
        command_line = f'schtasks /F /create /ru "SYSTEM" /tn "{task_name}" /tr "{command}" /sc {schedule}'
        subprocess.run(command_line, shell=True, check=True)
        print(f"Windows task '{task_name}' created successfully.")
    except subprocess.CalledProcessError as e:
        print(f"Failed to create Windows task. Error: {e}")

# query = "SELECT * FROM `Stines-GmbH`.`Kunden-Server` WHERE `IP-Adresse` = ""'{}'""".format(get_local_ip())

query = "SELECT * FROM `Stines-GmbH`.`Kunden-Server` WHERE `IP-Adresse` = ""'{}'""".format("172.19.1.6")

print("Before Get List")
print(mysql_connect.get_ip(query))
list = mysql_connect.get_ip(query)
print("Atfer Get IP")

if list == []:
    query_insert = f"INSERT INTO `Kunden-Server` (Name,`Server-Name`,`IP-Adresse`,Funktion,CPU,RAM,Speicher) VALUES ('unkown','{socket.gethostname()}','{get_local_ip()}','-','{system_info.get_cpu_info()}','{system_info.get_ram_info()}','{system_info.get_hdd_info()}')"
    print("List is Empty")
    mysql_connect.add_user(query_insert,"Stines-GmbH","")

set_ipaddress = []
print("Before Row")
# Ergebnisse durchlaufen und ausgeben
for row in list:
    name = row[2]
    ipadress = row[4]
    set_ipaddress = row[4]
    lastchange = row[6]
    funktion = row[7]
    token = row[8]
    print(name)

    cursor = mysql_connect.get_database()

    # Überprüfen, ob die Datenbank bereits existiert

    database_exists = False
    for (db_name,) in cursor:
        if name in str(db_name):
            database_exists = True
        if "-" in str(db_name):
            database_exists = True

    # Datenbank erstellen, wenn sie noch nicht existiert
    if not database_exists:
        create_database_query = f"CREATE DATABASE `{name}`"
        mysql_connect.create_database(create_database_query,name)
        print(f"Die Datenbank '`{name}`' wurde erfolgreich erstellt.")
    else:
        print(f"Die Datenbank '`{name}`' existiert bereits.")

    if token is not None:
        eval(funktion + '("' + ipadress + '","' + name + '","' + token + '")')
    else:
        if funktion == "-":
            break
        else:
            eval(funktion + '("' + ipadress + '","' + name + '")')

print(set_ipaddress)
system_info_get(f"{set_ipaddress}","Stines-GmbH")

task_name = "Reports"
command_to_execute = "C:\\Scripte\\Start.exe"
schedule = f"daily /st 23:{random.randint(0, 59)}"  # You can customize the schedule here

create_windows_task(task_name, command_to_execute, schedule)