import subprocess
import json
import datetime
import socket
import requests
import platform

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 request(function,variable):
    url = (f"http://api.stines.de:8001/{function}")
    response = requests.post(url,json = variable,headers={'access_token':'^YWUbG7yX*V!tV^KBSd*2c&vdN3wV9a2i7f3hfGFMBYFxi6#mMiJGiaA5KEHE%B*miK%qb7rQ67gmcYP@gqmux8'})
    return response

def getdabase():
    return request("info/getdatabase",{'ip':get_local_ip()})

def server_exist(hostname):
    return request("info/getserver",{'name': hostname, 'dbase': getdabase()})


def request(function,variable):
    url = (f"http://api.stines.de:8001/{function}")
    response = requests.post(url,json = variable,headers={'access_token':'^YWUbG7yX*V!tV^KBSd*2c&vdN3wV9a2i7f3hfGFMBYFxi6#mMiJGiaA5KEHE%B*miK%qb7rQ67gmcYP@gqmux8'})
    return response



# PowerShell-Skript für die Active Directory-Abfrage
# powershell_script = r'''
# # PowerShell-Skript für die Active Directory-Abfrage mit Filter
# $ADResults = Get-ADUser -Filter { (ObjectClass -eq "user") -and (-not (UserPrincipalName -like "*Mailbox*")) -and (-not (UserPrincipalName -like "*Admin*")) -and (-not (UserPrincipalName -like "*Exchange*"))} -Properties sn,GivenName,SamAccountName,WhenCreated,WhenChanged,LastLogon,EmailAddress |
#     Select-Object sn,GivenName,SamAccountName,WhenCreated,WhenChanged,LastLogon,EmailAddress |
#     ConvertTo-Json -Depth 1 | Out-File -Encoding UTF8 output.json
#
# # Ausgabe der JSON-Daten
# $ADResults
# '''
#
# # PowerShell-Skript ausführen und die Ausgabe abrufen
# result = subprocess.run(["powershell", "-command", powershell_script], stdout=subprocess.PIPE, text=True)
#
with open('output.json', 'r',encoding='utf-8-sig') as file:
    ad_data = json.load(file)

# Ergebnisse anzeigen oder weiterverarbeiten
    for entry in ad_data:
        samaccountname = entry['SamAccountName']
        user_disabled = request("checkdisabledduser", {"user": f'{samaccountname}', "dbname": 'tnp-Invest-GmbH'}).json()
        for i in user_disabled:
            if i[1] is None:
                next
            else:
                print(f"{i[1]} - {i[0]} - {samaccountname}")
                subprocess.run(["powershell", "-command", f"Remove-ADGroupMember -Identity '{i[0]}' -Members '{samaccountname}'"], stdout=subprocess.PIPE, text=True)


#         createdate = when_created.strftime('%Y-%m-%d %H:%M:%S')
#         changedate = WhenChanged.strftime('%Y-%m-%d %H:%M:%S')
#         print(vorname)
#         if entry['EmailAddress'] is None:
#             mail = "-"
#         else:
#             mail = entry['EmailAddress']
#
#         if get_user_exist(samaccountname).text == "false":
#             print(request("ad/reportadduser", {
#                 "query": f"INSERT INTO User (Name, Vorname, SamAccountName,CreateDate, ChangeDate,LastLogon,`E-Mail-Adresse`) VALUES ('{name}','{vorname}','{samaccountname}','{createdate}','{changedate}','{lastlogon}','{mail}')",
#                 'dbname': getdabase().text.replace('"', '')}))
#         else:
#             print(request("ad/reportadduser", {
#                 "query": f"UPDATE User SET Name = '{name}', Vorname = '{vorname}', SamAccountName = '{samaccountname}',CreateDate = '{createdate}', ChangeDate = '{changedate}',LastLogon = '{lastlogon}',`E-Mail-Adresse` = '{mail}' WHERE SamAccountName = '{samaccountname}'",
#                 'dbname': getdabase().text.replace('"', '')}))

# with open('group_members_old.json', 'r', encoding='utf-8-sig') as file:
#     group_data = json.load(file)
#
# # Iterieren Sie über die Gruppen und ihre Mitglieder und zeigen Sie sie an
# for group_name, members in group_data.items():
#     getgroup = get_group_exist(group_name).text
#
#     if getgroup == "false":
#             request("report/addgroup", {'query': f"INSERT INTO Gruppen (Name) VALUES ('{group_name}')",'dbname': getdabase().text.replace('"', '')})
#     else:
#         print(f"{getgroup} - {group_name}")
#         if isinstance(members, list):
#             for member in members:
#                 getuserID = request("report/getuserid", {'dbname': getdabase().text.replace('"', ''), "user": member['SamAccountName']})
#                 addusertogroup = request("report/addusertogroup", {'userID': getuserID.text, "groupID": getgroup, 'dbname': getdabase().text.replace('"', '')})
#                 if getuserID.text == "false":
#                     next
#                 else:
#                     print(addusertogroup.text)
#                     print(getuserID.text)
#         elif isinstance(members, dict):
#             getuserID = request("report/getuserid",
#                                 {'dbname': getdabase().text.replace('"', ''), "user": members['SamAccountName']})
#             if getuserID.text == "false":
#                 next
#             else:
#                 print(getuserID.text)