import os
import subprocess
import requests
import time
import socket
import datetime
import system_info
import net_volume

def request(function,variable): ##API-Server
    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 space_free():
    space_free = str(system_info.get_single_hdd("free")).replace("['", "").replace("]", "").replace("'", "").replace(
        ",", ";")  ## FREE SPACE OF VOLUME
    return space_free

def space_used():
    space_used = str(system_info.get_single_hdd("used")).replace("['", "").replace("]", "").replace("'", "").replace(
        ",", ";")  ## USED SPACE OF VOLUME
    return space_used

def space_total():
    space_total = str(system_info.get_single_hdd("total")).replace("['", "").replace("]", "").replace("'", "").replace(
        ",", ";")  ## TOTAL SPACE OF VOLUME
    return space_total


# def pushover_send(errorcode,hostname): ## SEND PUSHOVER
#     variable = {"token": "az8aqcsg45ikm73q3ry34vxs2z9kgj","user": "uo2sf2pmrtjvt8auu786fviabimimr","message":f"{errorcode}","title":f"VOLUME_MOUNT ERROR on HOST:{hostname}"}
#     requests.post("https://api.pushover.net:443/1/messages.json",variable, {"Content-type": "application/x-www-form-urlencoded"})


hostname = socket.gethostname() ## GET HOSTNAME
user = "" ## GET CURRENT USER
system_type = system_info.get_client_info()

## Check Database
if system_type == "Client":
    type = "Dhcp"
else:
    type = "Manual"

database = request("host/get/database", {"ip": system_info.get_local_ip(type)}).text.replace('"','')  ##GET DATABASE FROM SQL-SERVER
print(database)
check_hostname = request("host/get",{"hostname":hostname,"dbname":database}) ##GET VOLUMES FROM SQL-SERVER
print(check_hostname)


if system_type == "Client":
    if system_info.get_smb_credential() == None:
        user = request("client/user/get", {"hostname": hostname, "dbname": database}).text.replace('"','')
    else:
        user = system_info.get_smb_credential()
else:
    user = os.getlogin()

### Check User
check_user_exist = request("user/get",{"user":user,"dbname":database})
if check_user_exist.text == "false":
    request("user/set", {"user": user, "dbname": database,"hardwareID": check_hostname.text})
else:
    if system_type == "Client":
        next
    else:
        request("user/set/lastlogon", {"userID": check_user_exist.text, "dbname": database, "lastlogon": system_info.get_lastlogon(user)})


## Check Host
if check_hostname.text == "false":
    request("host/set",{"hostname":hostname,"user": os.getlogin(),"ipadresse":system_info.get_local_ip(type),"winver":system_info.get_winver(),"cpuname":system_info.get_cpu_brand(),"cores":system_info.get_cpu_core(),"ram":system_info.get_ram_info(),"hddused":space_used(),"hddfree":space_free(),"hddtotal":space_total(),"netvolumeuser":user,"dbname":database})
else:
    request("host/update",
            {"hostname":hostname,"user": os.getlogin(),"ipadresse":system_info.get_local_ip(type),"winver":system_info.get_winver(),"cpuname":system_info.get_cpu_brand(),"cores":system_info.get_cpu_core(),"ram":system_info.get_ram_info(),"hddused":space_used(),"hddfree":space_free(),"hddtotal":space_total(),"netvolumeuser":user,"dbname":database})


### Check NetVolume Exist
netvolume = request("host/get/netvolume",{"user":user,"dbname":database})

if netvolume.text == "false":
   print(net_volume.get_netvolume())
   if net_volume.get_netvolume() is None:
       with open("log.txt", "a") as datei: ## Schreibt ergebnissse in Log File
           datei.writelines(f"Keine Netvolume vorhanden!" + "\n")  ## WRITE TO ERRORLOG
       # pushover_send("Keine Netvolume vorhanden!", hostname)  ## SEND ERROR LOG TO PUSHOVER
else:
   for i in netvolume.json(): ##LIST FORM netvolume
       print(f" {i[2]} {i[1]}")
       if i != "-":
           if not os.path.isdir(f"{i[1]}"):
               errorcode = ""
               try:
                   if "%USERNAME%" in i[0]:
                       volume = i[0].replace("%USERNAME%",f"{user}")
                       name = i[2].replace("%USERNAME%","Home")
                   else:
                       volume = i[0]
                       name = i[2]
                   subprocess.run(["net", "use", f"{i[1]}:", f"{volume}"], capture_output=True, check=True) ## MOUNT VOLUME
                   script = fr'''$shell = New-Object -ComObject Shell.Application
                                 $shell.NameSpace("{i[1]}:").Self.Name = "{name}"''' ### Schreibt den Namen der Netzlaufwerke um
                   subprocess.run(["powershell", "-Command", script], capture_output = True,text = True)
               except subprocess.CalledProcessError as e:
                   time = datetime.datetime.now().strftime("%d.%m.%Y %H:%M")
                   if "85" in str(e.stderr):
                       print(f"{time} - Volume exists {i[0]} {i[1]}")
                   elif "1223" in str(e.stderr):
                       errorcode = f"{time} - {user} has no access to {i[0]} {i[1]}"
                   elif "53" in str(e.stderr):
                       errorcode = f"{time} - Volume was not Found {i[0]} {i[1]}"
                   elif "64" in str(e.stderr):
                       errorcode = f"{time} - Volume Path not found {i[0]} {i[1]}"
                   elif "1219" in str(e.stderr):
                       errorcode = f"{time} - Multiconnection to Folder not allow {i[0]} {i[1]}"
                   else:
                       errorcode = f"{time} - Unknow ERROR Code {str(e.stderr)}"

                   request("report/errorlog",{"datum": time,"hostname":hostname,"samaccountname":user,"errorcode":errorcode})

# #         # pushover_send(errorcode, hostname)  ## SEND ERROR LOG TO PUSHOVER
# #
# # while True:
# #     check_volume_exist()
# #     time.sleep(60)