from setuphelpers import *
from setupdevhelpers import *

def update_package():
    # Déclaration des variables locales
    package_updated = False
    proxies = get_proxies()
    if not proxies:
        proxies = get_proxies_from_wapt_console()
    
    base_url = "https://mirror.cyberbits.eu/gnu/emacs/windows/"

    tr = sorted(table_to_list(bs_find(base_url, 'table')))

    latest_dir = max(tr)
        
    latest_url = base_url + latest_dir

    find_all = bs_find_all(latest_url,"a","href")
    for find in find_all:
        if find["href"].endswith(".exe"):
            latest_bin = find["href"].split("/")[-1]
            download_url = latest_url + latest_bin
            version = latest_bin.split("-")[1]
            
    print(f"Dernière version trouvée : emacs-{version}")
    print(f"URL de téléchargement de l'installateur : {download_url}")


    # Supprimer les anciens fichiers installateurs
    for f in glob.glob("*.exe"):
        if f != latest_bin:
            remove_file(f)

    # Télécharger le dernier installateur
    wget(download_url, latest_bin, proxies=proxies)

    # Mettre à jour la version du logiciel dans le fichier de contrôle
    control.set_software_version(version)
    control.save_control_to_wapt()

def table_to_list(table):
        result = []
        for row in table.find_all('tr')[1:]:
            td = row.find_all('td')[1].get_text(strip = True)
            if td.startswith("emacs-"):
                result.append(td)
        return result