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

# Declaring global variables - Warnings: 1) WAPT context is only available in package functions; 2) Global variables are not persistent between calls


def update_package():
    result = False
    proxies = get_proxies()

    if not proxies:
        proxies = get_proxies_from_wapt_console()
    dict_arch ={
        "x64":"-win64.zip",
        "x86": "-win32.zip"
    }
    git_repo = "minetest/minetest"
    url_api = "https://api.github.com/repos/%s/releases" % git_repo   
    # Getting latest version information from official sources
    print("API used is: %s" % url_api)
    json_load = json.loads(wgets(url_api, proxies=proxies))
    url_dl = None
    # Itérer sur chaque release pour trouver la dernière version correspondante
    for release in json_load:
        if "assets" in release:
            for download in release["assets"]:
                if download["browser_download_url"].endswith('.zip') and dict_arch[control.architecture] in download["browser_download_url"]:
                    url_dl = download["browser_download_url"]
                    version = release["tag_name"]
                    filename= download["name"]
                    break
        if url_dl:
            break  # Sortir de la boucle externe si la bonne version est trouvée

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

    #nettoyer les fichiers temporaires
    for f in glob.glob('*.zip'):
        if f != filename:
            remove_file(f)
    
    control.set_software_version(version)
    control.save_control_to_wapt()