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"
    api_url = f"https://api.github.com/repos/{git_repo}/releases/latest"
    os_dict = {"windows": ".msi", "debian_based": ".deb", "redhat_based": ".rpm", "darwin": "-x64.zip"}

    # Getting latest version information from official sources
    print("API used is: %s" % api_url)
    json_load = json.loads(wgets(api_url, proxies=proxies))
    for to_download in json_load["assets"]:
        if os_dict[control.target_os] in to_download["name"] and "java24" in to_download['name']:
            download_url = to_download["browser_download_url"]
            version = json_load["tag_name"].split("-")[0]
            latest_bin = to_download["name"]
            break

    # Deleting outdated binaries
    remove_outdated_binaries(version)

    # Downloading latest binaries
    print("Latest %s version is: %s" % (control.name, version))
    print("Download URL is: %s" % download_url)
    if not isfile(latest_bin):
        print("Downloading: %s" % latest_bin)
        wget(download_url, latest_bin, proxies=proxies)
    else:
        print("Binary is present: %s" % latest_bin)

    control.set_software_version(version)
    control.save_control_to_wapt()