
# -*- 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()
    app_name = control.name

    api_url = f"https://www.pingplotter.com/versioncheck/v2/p?os=win&force=1"
    releases_dict = wgets(api_url, proxies=proxies, as_json=True)
    version = releases_dict["NewVersion"]
    download_url = releases_dict["DownloadURL"]
    latest_bin = download_url.rsplit("/", 1)[-1]
    latest_bin_extension = latest_bin.rsplit(".", 1)[-1]

    print(f"Latest {app_name} version is: {version}")

    # Downloading latest binaries
    print(f"Download URL is: {download_url}")
    if isfile(latest_bin):
        remove_file(latest_bin)

    print(f"Downloading: {latest_bin}")
    wget(download_url, latest_bin, proxies=proxies)
    print(f"Binary is present: {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'*.{latest_bin_extension}'):
        if f != latest_bin:
            remove_file(f)

    control.set_software_version(version)
    control.save_control_to_wapt()

    return package_updated
