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

def update_package():
    # Declaring local variables
    package_updated = False

    proxies = get_proxies_from_wapt_console()
    if not proxies:
        proxies = get_proxies()
    app_name = control.name

    if control.architecture == "x64":
        download_url = "https://download.keepersecurity.com/forcefield/keeperforcefield.msi"

    else:
        download_url = "https://download.keepersecurity.com/forcefield/arm64/keeperforcefield.msi"

    version = wgets("https://download.keepersecurity.com/forcefield/version.json", as_json=True)["version"]
    latest_bin = download_url.rsplit("/", 1)[-1]

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

    # Downloading latest binaries
    print("download_url is: %s" % download_url)
    if not isfile(latest_bin):
        print("Downloading: %s" % latest_bin)
        wget(download_url, latest_bin, proxies=proxies)
        package_updated = True
    else:
        print("Binary is present: %s" % latest_bin)

    version = 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)})")

    # Mettre à jour le package
    control.set_software_version(version)
    control.save_control_to_wapt()

    return package_updated