# -*- coding: utf-8 -*-
from setuphelpers 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
    url = "https://imagemagick.org/script/download.php"
    bin_contains = "x64-dll.exe"

    # Getting latest version from official sources
    print("URL used is: %s" % url)
    for bs_search in bs_find_all(url, "a", proxies=proxies, timeout=10):
        if bin_contains in bs_search.text:
            download_url = bs_search["href"]
            latest_bin = bs_search["href"].split("/")[-1]
            version = ".".join([latest_bin.split("-")[1], latest_bin.split("-")[2]])
            break

    # Downloading latest binaries
    print("Latest %s version is: %s" % (app_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)
    if Version(version_from_file) != Version(version) and version_from_file != "":
        version = version_from_file
    else:
        print("Binary file version corresponds to online version")

    # Changing version of the package
    if Version(version) > Version(control.get_software_version()):
        print("Software version updated (from: %s to: %s)" % (control.get_software_version(), Version(version)))
        package_updated = True
    else:
        print("Software version up-to-date (%s)" % Version(version))
    control.set_software_version(version)
    control.save_control_to_wapt()

    # Deleting outdated binaries
    for exe in glob.glob('*.exe'):
        if exe != latest_bin:
            remove_file(exe)

    # Validating or not update-package-sources
    return package_updated
