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


def update_package():
    # Declaration of local variables
    package_updated = False
    proxies = get_proxies_from_wapt_console()
    if not proxies:
        proxies = get_proxies()
    api_url = "https://www.influxdata.com/versions.json"

    # Get JSON data from API
    api_dict = wgets(api_url, proxies=proxies, as_json=True)

    # Check if key 'telegraf stable' exists in dictionary
    if "telegraf_stable" in api_dict:
        # Obtenir les informations sur la dernière version de Telegraf
        latest_info_version = api_dict["telegraf_stable"]

        # Extraire la dernière version
        latest_version = latest_info_version.get('version', 'Version inconnue').lstrip('v')
        
        print(f"La dernière version stable de telegraf est : {latest_version}")

        # Chercher l'URL de téléchargement pour Windows
        url_windows = None
        for download in latest_info_version['downloads']:
            if download['ref'] == 'win':
                url_windows = download['code'][0].split(" ")[1]
                break

        if url_windows:
            print(f"L'URL de téléchargement pour Windows est : {url_windows}")
        else:
            print("L'URL de téléchargement pour Windows n'a pas été trouvée.")

    filename= url_windows.split("/")[-1]    

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

    if not isfile(filename):
        wget(url_windows, filename, proxies=proxies)

    setup_file = unzip(filename,("."))
    extracted_file_path = setup_file[0] 
    remove_file(filename)
           
    if extracted_file_path != filename:
        for existing_file in glob.glob("*.exe"):
            if existing_file != os.path.basename(extracted_file_path):  # Comparaison avec le nom de fichier seulement
                remove_file(existing_file)
    # Updating the package
    control.set_software_version(latest_version)
    control.save_control_to_wapt()

    return package_updated       