import os
import subprocess
import requests
import time
import socket
import datetime
import create_service
import system_info
import volume

create_service.addservice("VOLUME_CHECK") ## CREATE 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 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"})

def check_volume_exist():
    hostname = socket.gethostname() ## GET HOSTNAME
    user = os.getlogin() ## GET CURRENT USER
    database = request("info/getclient",{"name":hostname}).text.replace('"',"") ##GET DATABASE FROM SQL-SERVER
    volume_get = request("info/getvolume",{"name":hostname,"database":database}) ##GET VOLUMES FROM SQL-SERVER

    space_free = str(system_info.get_single_hdd("free")).replace("['","").replace("]","").replace("'","").replace(",",";") ## FREE SPACE OF VOLUME
    space_used = str(system_info.get_single_hdd("used")).replace("['","").replace("]","").replace("'","").replace(",",";") ## USED SPACE OF VOLUME
    space_total = str(system_info.get_single_hdd("total")).replace("['","").replace("]","").replace("'","").replace(",",";") ## TOTAL SPACE OF VOLUME

    if volume_get.text == "false":
        netvolume = volume.get_netvolume()
        values = (
            f"'{hostname}','{system_info.get_local_ip()}','{system_info.get_winver()}','{system_info.get_cpu_brand()}','{system_info.get_cpu_core()}','{system_info.get_ram_info()}','{space_total}','{space_free}','{space_used}'")

        for idx in range(9, 19): ## ADD VOLUMES FROM VOLUME_GET
            if idx - 9 < len(netvolume):
                netvolume_value = netvolume[idx - 9].replace("\\", "\\\\")
                values += f", '{netvolume_value}'"
            else:
                values += ", '-'"
        query = f"INSERT INTO `Clients` (`Name`,`IP-Adresse`,`Windows-Version`,`CPU-Name`,`Prozessor-Anzahl`,`RAM`,`Speichergesamt`,`Speicherfrei`,`Speicherbelegt`,`Netzlaufwerk_1`,`Netzlaufwerk_2`,`Netzlaufwerk_3`,`Netzlaufwerk_4`,`Netzlaufwerk_5`,`Netzlaufwerk_6`,`Netzlaufwerk_7`,`Netzlaufwerk_8`,`Netzlaufwerk_9`,`Netzlaufwerk_10`) VALUES ({values})"
        request("info/addclient",{"query":query,"database":database}) ## ADD CLIENT IF NOT EXIST
    else:
        for i in volume_get.json()[0]: ##LIST FORM VOLUME_GET
            if i != "-":
                if not os.path.isdir(f"{i}"):
                    i = str(i).split(';') ## SPLIT i from X:;\\172.19.1.3
                    try:
                        result = subprocess.run(["net", "use", f"{i[0]}", f"{i[1]}"], capture_output=True, check=True) ## MOUNT VOLUME
                    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)}"


        with open("log.txt", "a") as datei:
            datei.writelines(f"{errorcode}" + "\n") ## WRITE TO ERRORLOG
        pushover_send(errorcode, hostname)  ## SEND ERROR LOG TO PUSHOVER

while True:
    check_volume_exist()
    time.sleep(60)