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

def update_package():
    # Declaring local variables
    package_updated = False
    proxies = get_proxies()
    if not proxies:
        proxies = get_proxies_from_wapt_console()
    update_dict = {
        "arm64" : "-arm64",
        "x64" : "-amd64"
    }
    url_api = "https://gitea.com/api/v1/repos/gitea/tea/releases/latest"
    # Getting latest version information from official sources
    print(f"API used is: {url_api}")
    json_load = json.loads(wgets(url_api, proxies=proxies))
    for download in json_load["assets"]:
        if download["browser_download_url"].endswith(".exe") and update_dict[control.architecture] in download["browser_download_url"] :
            url_dl = download["browser_download_url"]
            version = json_load["tag_name"].replace("v","")
            filename = download["name"]
            break

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

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