import urllib.parse
import os
from setuphelpers import *
from setupdevhelpers import *
import glob


def update_package():
    # Déclaration des variables locales
    package_updated = False
    proxies = get_proxies_from_wapt_console()
    if not proxies:
        proxies = get_proxies()

    dict_arch = {"x64": "x64-Setup.exe", "x86": "x86-Setup.exe"}

    url_base = "https://www.voidtools.com/downloads/"
    response = requests.get(url_base, proxies=proxies)
    response.raise_for_status()

    for elem in bs_find_all(response.content, "a", "href"):
        href = elem.get("href")
        if href.endswith(dict_arch[control.architecture]):
            url_download = urllib.parse.urljoin(url_base, href)
            print("URL de téléchargement:", url_download)
            break

    filename = url_download.split("/")[-1]
    print("Nom du fichier:", filename)
    last_version = filename.split("-")[-2]
    print("Dernière version:", last_version)

    if not isfile(filename):
        package_updated = True
        wget(url_download, filename, proxies=proxies)
        print("Téléchargé:", filename)

    last_version = get_file_properties(filename)["ProductVersion"]

    for f in glob.glob("*.exe"):
        if f != filename:
            remove_file(f)

    control.set_software_version(last_version)
    control.save_control_to_wapt()

    return package_updated
