import os
from multiprocessing import freeze_support
import cpuinfo
import psutil
import math
import platform
import datetime
import socket
import subprocess
import re
import wmi

def get_cpu_brand():
    freeze_support()
    return cpuinfo.get_cpu_info()['brand_raw']


def get_cpu_core():
    freeze_support()
    return os.cpu_count()

def get_cpu_ghz():
    freeze_support()
    ghz = str(cpuinfo.get_cpu_info()['hz_actual_friendly'])
    return ghz.replace(" GHz","")[:-2]

def get_cpu_typ():
    battery_check = psutil.sensors_battery()
    if battery_check is None:
        return "static"
    else:
        return "mobile"

def get_mainboard_model():
    return f"'{wmi.WMI().Win32_ComputerSystem()[0].Model}'"

def get_mainboard_vendor():
    return f"'{wmi.WMI().Win32_ComputerSystem()[0].Manufacturer}'"

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_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 get_single_hdd(function):
    freeze_support()
    used_disk_size = 0
    disk_partitions = psutil.disk_partitions()
    partition_return = []
    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)
        partition_name = partition.mountpoint.replace(':\\',"")
        partition_return.append(f"{partition_name}: {space}GB")
    return partition_return

def get_winver():
    freeze_support()
    return platform.platform()

def get_local_ip(type):
    powershell_script = '''
    Get-NetIPAddress | Where-Object { $_.PrefixOrigin -eq '''f'"{type}"'''' -and $_.InterfaceAlias -like "*Ethernet*" } | Select-Object -ExpandProperty IPAddress
    '''
    result = subprocess.check_output(["powershell.exe", "-command", powershell_script], universal_newlines=True)#
    ip = result.rsplit('.',1)
    ip = ip[0] + '.' + "0"
    return ip

def get_lastlogon(user):
        # PowerShell-Befehl als Zeichenfolge erstellen
        output = subprocess.check_output(["quser", user], universal_newlines=True)

        # Wenn der Befehl erfolgreich ist, wird die Ausgabe hier verarbeitet
        lines = output.strip().split('\n')
        if len(lines) > 1:
            # Die zweite Zeile enthält die Anmeldeinformationen, z.B.: "rdpadmin  rdp-tcp#96  5  Aktiv  30.10.2023 13:36"
            info = lines[1].split()
            last_logon_date = info[-2]
            last_logon_time = info[-1]
            result = f"{last_logon_date}{last_logon_time}"
        else:
            result = False
        return result

def get_client_info():
    powershell_script = f'''Get-WmiObject -Class Win32_OperatingSystem | Select-Object -ExpandProperty ProductType'''
    result = subprocess.check_output(["powershell.exe", "-command", powershell_script], universal_newlines=True)
    if result[0] == "1":
        return "Client"
    else:
        return "Server"

def get_smb_credential():
    try:
        output = subprocess.check_output(['wmic', 'netuse', 'get', 'UserName'], universal_newlines=True)
        lines = output.strip().split('\n')
        # Entfernen Sie den Header "UserName" (erste Zeile)
        if len(lines) >= 2:
            usernames = lines[2:]  # Alle Zeilen außer der ersten Zeile
            for username in usernames:
                return username.split("\\")[1]
    except:
        return False