from setuphelpers import *
import requests
import re
import json

def update_package():
    # Déclarer les variables locales
    result = False
    proxies = get_proxies()
    if not proxies:
        proxies = get_proxies_from_wapt_console()
    git_repo = "JOSM/josm"
    url_api = f"https://api.github.com/repos/{git_repo}/releases/latest"
    
    bin_ends = ".msi"
    bin_contains = "JOSM-Windows-java"

    # Obtenir la dernière version à partir des sources officielles
    print("API used is: %s" % url_api)
    json_load = json.loads(wgets(url_api, proxies=proxies))

    assets = json_load.get('assets', [])
    version = json_load.get('tag_name').split('-')[0]  # Extraire la version de JOSM

    latest_java_version = -1
    latest_asset = None

    # Utiliser une regex pour extraire la version de Java du nom de fichier
    java_version_pattern = re.compile(r'JOSM-Windows-java(\d+)-\d+\.msi')

    for asset in assets:
        if bin_contains in asset['name'] and bin_ends in asset['name']:
            match = java_version_pattern.match(asset['name'])
            if match:
                java_version = int(match.group(1))
                if java_version > latest_java_version:
                    latest_java_version = java_version
                    latest_asset = asset

    if latest_asset:
        filename = latest_asset['name']
        download_url = latest_asset['browser_download_url']

        if not isfile(filename):
            package_updated = True
            wget(download_url, filename, proxies=proxies)

        # Nettoyer les fichiers temporaires
        for f in glob.glob('*.exe'):
            if f != filename:
                remove_file(f)

        version = get_version_from_binary(filename).split(".")[-1]

        control.set_software_version(version)
        control.save_control_to_wapt()