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

def update_package():
    # Declaring local variables
    package_updated = False
    proxies = get_proxies()
    if not proxies:
        proxies = get_proxies_from_wapt_console()

    url = "https://esante.gouv.fr/services/espace-cps/telechargements-libres/cryptolib-cps-windows"

    # Getting latest version from official sources
    print("URL used is: %s" % url)
    for bs_search in bs_find_all(url, "a", "href", proxies=proxies):
        if  bs_search['href'].endswith(".exe"):
            download_url = "https://esante.gouv.fr" + bs_search["href"]
            latest_bin = download_url.split("/")[-1]
            version = latest_bin.split("-")[1].split("_")[0].rsplit(".",1)[0]
            break

    # Downloading latest binaries
    print("Latest %s version is: %s" % (control.name, version))
    print("Download URL is: %s" % download_url)
    if not isfile(latest_bin):
        print("Downloading: %s" % latest_bin)
        wget(download_url, latest_bin, proxies=proxies)
    else:
        print("Binary is present: %s" % latest_bin)

    # Checking version from file
    version_from_file = get_version_from_binary(latest_bin)
    # Changing version of the package
    if Version(version) > Version(control.get_software_version()):
        print(f"Software version updated (from: {control.get_software_version()} to: {Version(version)})")
        package_updated = True
    else:
        print(f"Software version up-to-date ({Version(version)})")

    for f in glob.glob(f'*.exe'):
        if f != latest_bin:
            remove_file(f)

    control.set_software_version(version)
    control.save_control_to_wapt()

    return package_updated