import requests
import shutil
import subprocess
import os
import toml
import string
import secrets
import mysql_connect
from kundennummer import create_gui
import time
import pyperclip
import socket
from datetime import datetime
import socket

def get_hostname():
    print(socket.gethostname())
    return (socket.gethostname())

def get_local_ip():
    try:
        # Socket erstellen, um die lokale IP-Adresse zu ermitteln
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(("8.8.8.8", 80))  # Eine temporäre Verbindung zu einem externen Server herstellen

        # Die lokale IP-Adresse aus den Socketeigenschaften abrufen
        local_ip = s.getsockname()[0]

        # Den Socket schließen
        s.close()

        return local_ip
    except Exception as e:
        print(f"Fehler beim Abrufen der lokalen IP-Adresse: {e}")
        return None

def generate_password(length=8):
    characters = string.ascii_letters + string.digits

    # Hinzufügen der gewünschten Sonderzeichen
    special_characters = "!@#$%&"
    characters += special_characters

    # Passwort generieren
    password = ''.join(secrets.choice(characters) for i in range(length))
    return password

password = generate_password()

def download_latest_rustdesk():
    # URL zum RustDesk-Repository
    url = 'https://api.github.com/repos/rustdesk/rustdesk/releases/latest'

    # Anfrage an die Github-API, um das neueste Release zu finden
    response = requests.get(url)
    release_data = response.json()

    # URL der .exe-Datei des neuesten Releases finden
    download_url = next((asset['browser_download_url'] for asset in release_data['assets'] if asset['name'].endswith('x86_64.exe')), None)

    if download_url:
        # Herunterladen der .exe-Datei
        try:
            os.mkdir("C:\\temp")
        except:
            next
        exe_response = requests.get(download_url, stream=True)
        rustdesk_exe = "C:\\temp\\Rustdesk-host=remote.stines.de,key=QViLr1r9LsKiEWoMgA26pNGqgkyDXcZpvXqepqoa934=.exe"
        with open(rustdesk_exe, 'wb') as file:
            shutil.copyfileobj(exe_response.raw, file)
        subprocess.Popen(f"{rustdesk_exe} --silent-install")

        # Warte auf den Abschluss des Subprozesses und erhalte die Ausgabe
        time.sleep(6)
        subprocess.run("taskkill /IM cmd.exe")

        print(f'RustDesk {release_data["tag_name"]} wurde erfolgreich als RustDesk.exe heruntergeladen.')
    else:
        print('Die neueste Version von RustDesk konnte nicht gefunden werden.')

def start_and_stop_rustdesk():
    subprocess.Popen(f"C:\\Program Files\\RustDesk\\rustdesk.exe --password {password}")
    time.sleep(1)
    subprocess.run("taskkill /IM rustdesk.exe")

def edit_toml():
    appdata_path = os.environ['APPDATA']
    file_path = f"{appdata_path}\\RustDesk\\config\\RustDesk2.toml"
    data = toml.load(file_path)
    data['options']['allow-remote-config-modification'] = 'Y'
    data['options']['relay-server'] = "remote.stines.de"
    data['options']['key'] = "QViLr1r9LsKiEWoMgA26pNGqgkyDXcZpvXqepqoa934="
    data['options']['verification - method'] = 'use-permanent-password'
    with open(file_path, 'w') as file:
        toml.dump(data, file)

def handle_submit():
    result_container = []
    create_gui(result_container)
    return result_container[0]

def get_firmenname():
    query = f"SELECT DISTINCT name FROM `Stines-GmbH`.`Kunden-Server` where Kundennummer = {handle_submit()}"
    return mysql_connect.get_user(query,'Stines-GmbH',"")

def create_database(name):
    table_name = "Rustdesk-Clients"
    create_table_query = f"CREATE TABLE IF NOT EXISTS `{table_name}` (id INT AUTO_INCREMENT PRIMARY KEY, importdate BIGINT(11), `Rustdesk-ID` TEXT, `Rustdesk-Password` TEXT,Hostname TEXT, `IP-Adresse` TEXT)"
    mysql_connect.create_database(create_table_query, name)

def get_rustdesk_id():
        subprocess.Popen("C:\Program Files\RustDesk\\rustdesk.exe --get-id",creationflags=subprocess.CREATE_NO_WINDOW,stdout=subprocess.PIPE,stderr=subprocess.PIPE,stdin=subprocess.PIPE)
        time.sleep(1)
        subprocess.run("taskkill /IM rustdesk.exe")
        return pyperclip.paste()


## Download Rustdesk
download_latest_rustdesk()

start_and_stop_rustdesk()

## Edit Toml
edit_toml()

## Get Firmenname
firmenname = get_firmenname()[0][0]
create_database(firmenname)

# ###Create Query for Import
query = f"INSERT INTO `Rustdesk-Clients` (importdate,`Rustdesk-ID`,`Rustdesk-Password`,Hostname,`IP-Adresse`) VALUES (%s,%s,%s,%s,%s)"
values=(int(datetime.now().timestamp()),get_rustdesk_id(),password,get_hostname(),get_local_ip())
mysql_connect.add_user(query,firmenname,values)


subprocess.Popen(f"C:\\Program Files\\RustDesk\\rustdesk.exe")