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


def update_package():
    # Declaring local variables
    package_updated = False
    proxies = get_proxies()
    if not proxies:
        proxies = get_proxies_from_wapt_console()
    update_dict = {"windows": "x64"}
    api_url = "https://api.github.com/repos/TheJoeFin/Text-Grab/releases/latest"

    # Get data from API
    releases_dict = json.loads(wgets(api_url, proxies=proxies))
    zip_found = False  # Flag pour indiquer la découverte d'un fichier .zip
    for release in releases_dict:
        if zip_found:
            break
        for asset in releases_dict["assets"]:
            if asset["browser_download_url"].endswith(".zip") and update_dict[control.target_os] in asset["browser_download_url"]:
                url_download = asset["browser_download_url"]
                latest_bin = url_download.split("/")[-1]
                version = releases_dict["tag_name"].replace("v", "").split("-")[0]
                zip_found = True  # Mettre à jour le flag pour indiquer qu'un zip a été trouvé
                break

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

    # Downloading latest binaries
    print("Download URL is: %s" % url_download)
    if not isfile(latest_bin):
        print("Downloading: %s" % latest_bin)
        wget(url_download, latest_bin, proxies=proxies)
    else:
        print("Binary is present: %s" % latest_bin)

    # Declaring local variables
    zip_name = glob.glob("Text-Grab-x64-*.zip")[0]
    unzip_dest = "."
    unzip(zip_name, unzip_dest)
    remove_file(zip_name)

    control.set_software_version(version)
    control.save_control_to_wapt()
