# from Controller import adcontroller_export, exchange_export, rds_export, smtp_export, zammad
import random
import subprocess
import socket
import os
import psutil
import math
import cpuinfo
from multiprocessing import freeze_support
import requests

## Gibt Name der Datei zum Debugen aus
filename = os.path.basename(__file__)

def request(function,variable):
    url = (f"http://127.0.0.1:8000/{function}")
    response = requests.post(url,json = variable)
    return response


def get_cpu_sql(cpu):
    freeze_support()
    requests = request("cpu_info",{'name':cpu})
    return requests.json()[0][0]

def get_ram_info():
    freeze_support()
    ram_info = psutil.virtual_memory()
    total_ram = ram_info.total / (1024 ** 3)  # In Gigabytes
    return math.ceil(total_ram)

def get_single_hdd(function):
    freeze_support()
    used_disk_size = 0
    disk_partitions = psutil.disk_partitions()
    print(disk_partitions)
    partition_return = []
    for partition in disk_partitions:
        partition_info = psutil.disk_usage(partition.mountpoint)
        print(partition.mountpoint.replace("\\",""))
        if function == "free":
            space = round(partition_info.free / (1024 ** 3), 2)
        elif function == "used":
            space = round(partition_info.used / (1024 ** 3), 2)
        elif function == "total":
            space = round(partition_info.total / (1024 ** 3), 2)
        partition_name = partition.mountpoint.replace(':\\',"")
        partition_return.append(f"{partition_name}: {space}GB")
    return partition_return

def get_total_hdd(function):
    freeze_support()
    space = 0
    disk_partitions = psutil.disk_partitions()
    for partition in disk_partitions:
        partition_info = psutil.disk_usage(partition.mountpoint)
        if function == "free":
            space += round(partition_info.free / (1024 ** 3), 2)
        elif function == "used":
            space += round(partition_info.used / (1024 ** 3), 2)
        elif function == "total":
            space += round(partition_info.total / (1024 ** 3), 2)
    return math.ceil(space)

def set_system_info(ipadress):
    freeze_support()
    cpu = ()
    cpu = cpuinfo.get_cpu_info()['brand_raw']
    # print('systeminfo_set',{'ram':get_ram_info(),'prozessor':get_cpu_sql(cpu),'cpu':cpu,'ipaddress':ipadress})
    single_free_hdd = str(get_single_hdd("free")).replace("['","").replace("]","").replace("'","")
    single_used_hdd = str(get_single_hdd("used")).replace("['","").replace("]","").replace("'","")
    single_total_hdd = str(get_single_hdd("total")).replace("['","").replace("]","").replace("'","")
    print(single_free_hdd)
    requests = request('systeminfo_set',{'ram':str(get_ram_info()),'prozessor':get_cpu_sql(cpu),'cpu':cpu,'ipaddress':ipadress,'single_free_hdd':single_free_hdd,'single_used_hdd':single_used_hdd,'single_total_hdd':single_total_hdd,'total_free_hdd':get_total_hdd("free"),'total_used_hdd':get_total_hdd("used"),'total_total_hdd':get_total_hdd("total")})
    print(requests.text)
    return print("Fin")

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()
        return local_ip
    except Exception as e:
        print(f"Fehler beim Abrufen der lokalen IP-Adresse: {e}")
        return None

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"{filename}-Windows task '{task_name}' created successfully.")
    except subprocess.CalledProcessError as e:
        print(f"{filename}-Failed to create Windows task. Error: {e}")

if __name__ == '__main__':
    freeze_support()
    try:
        print(get_local_ip())
        set_system_info(get_local_ip())
    except:
        print("Failed")

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.5")

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

print(list.text)
#
# set_ipaddress = []
# print(f"{filename}-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(f"{filename}-Inside Row {name}-{funktion}")
#
#     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
#     print(f"{filename}-{database_exists}")
#     if not database_exists:
#         create_database_query = f"CREATE DATABASE `{name}`"
#         mysql_connect.create_database(create_database_query,name)
#         print(f"{filename}-Die Datenbank '`{name}`' wurde erfolgreich erstellt.")
#     else:
#         print(f"{filename}-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(f"{filename}-FOR system_info_get: {set_ipaddress}")
#
#
#
# print(f"{filename}-FOR schedule: {ipadress}")
# 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)