# -*- coding: utf-8 -*-
from setuphelpers import *
from setupdevhelpers import *
import glob
import json

def update_package():
    # Declaring local variables
    proxies = get_proxies()
    if not proxies:
        proxies = get_proxies_from_wapt_console()

    os_dict = {
        "windows": ".msi",
        "redhat_based": ".rpm"
    }

    arch_dict = {
        "windows": {
            "x64": "x64",
            "arm64": "arm64",
        },
        "redhat_based": {
            "x64": "x86_64",
            "arm64": "aarch64",
        },
    }

    api_url = "https://api.github.com/repos/ibmruntimes/semeru26-binaries/releases/latest"
    os_suffix = os_dict[control.target_os]  #".msi", ".rpm"
    arch_prefix = arch_dict[control.target_os][control.architecture]   #"x64", "arm"

    releases_dict = json.loads(wgets(api_url, proxies=proxies))

    for asset in releases_dict["assets"]:
        url = asset["browser_download_url"]
        # Vérifie que l'URL se termine par l'extension OS ET contient le préfixe arch
        if (url.endswith(os_suffix) and arch_prefix in url and "jre" in url):
            url_download = url
            latest_bin = url.split("/")[-1]
            version = latest_bin.split("_")[-1].replace(os_suffix, "")
            exe_found = True
            break

    # Downloading latest binaries
    print("Download URL is: %s" % url_download)
    if isfile(latest_bin):
        remove_file(latest_bin)
    print("Downloading: %s" % latest_bin)
    wget(url_download, latest_bin, proxies=proxies)
    control.set_software_version(version)
    control.save_control_to_wapt()