# -*- 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":"-x64-gui.dmg",
        "x86" : ".dmg"    
        }
    
    url_api = "https://api.github.com/repos/duplicati/duplicati/releases" 
    # Getting latest version information from official source
    print("API used is: %s" % url_api)
    json_load = json.loads(wgets(url_api, proxies=proxies))

    # Vérifier que json_load est une liste
    if isinstance(json_load, list):
        # Itérer à travers chaque release
        for release in json_load:

            # Vérifier que la release contient une clé "assets" et que c'est une liste
            if "assets" in release and isinstance(release["assets"], list):
                found_valid_asset = False
                for download in release["assets"]:
                    # Vérifier si l'URL de téléchargement se termine par .dmg e
                    if download["browser_download_url"].endswith(".dmg") and dict_arch[control.architecture] in download["browser_download_url"] :
                        url_dl = download["browser_download_url"]
                        filename = download["name"]
                        version = release["name"][1:10].split("_")[0]
                        found_valid_asset = True
                        break
    #nettoyer les fichiers temporaires
    for f in glob.glob('*.dmg'):
        if f != filename:
            remove_file(f)

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

    control.set_software_version(version)
    control.save_control_to_wapt()