# -*- coding: utf-8 -*-
from setuphelpers import *
from setupdevhelpers import *
import re


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

    api_url = "https://api.github.com/repos/extrawurst/gitui/releases/latest"
    update_dict = {
        "windows-x64": "-win.msi",
    }
    # Get data from API
    releases_dict = json.loads(wgets(api_url, proxies=proxies))
    msi_found = False  # Flag pour indiquer la découverte d'un fichier .msi
    for release in releases_dict:
        if msi_found:
            break
        for asset in releases_dict["assets"]:
            if update_dict[control.target_os + "-" + ensure_list(control.architecture)[0]] in asset["browser_download_url"] and asset["browser_download_url"].endswith(".msi"):
                url_download = asset["browser_download_url"]
                latest_bin = url_download.split("/")[-1]
                version = releases_dict["name"].replace("v", "")
                msi_found = True  # Mettre à jour le flag pour indiquer qu'un msi a été trouvé
                break

    if not isfile(latest_bin):
        package_updated = True
        wget(url_download, latest_bin, proxies=proxies)

    # Deleting binaries
    for f in glob.glob("*.msi"):
        if f != latest_bin:
            remove_file(f)

    control.set_software_version(version)
    control.save_control_to_wapt()

    return package_updated
