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

# Declaring global variables - Warnings: 1) WAPT context is only available in package functions; 2) Global variables are not persistent between calls
app_name = "Process Explorer"


def update_package():
    # Declaring local variables
    result = False
    proxies = get_proxies()
    if not proxies:
        proxies = get_proxies_from_wapt_console()
    app_name = control.name
    url = "https://docs.microsoft.com/sysinternals/downloads/process-explorer#related-links"
    download_url = "https://download.sysinternals.com/files/ProcessExplorer.zip"
    latest_bin = download_url.split("/")[-1]

    # Getting latest version from official website
    print("URL used is: %s" % url)
    for bs_search in bs_find_all(url, "h1", proxies=proxies, timeout=10):
        if "Process Explorer" in bs_search.string:
            version = bs_search.string.replace("Process Explorer v", "")
            break

    print("Latest %s version is: %s" % (app_name, version))
    print("Download URL is: %s" % download_url)

    # Downloading latest binaries
    if isfile(latest_bin):
        remove_file(latest_bin)
    if not isfile(latest_bin):
        print("Downloading: %s" % latest_bin)
        wget(download_url, latest_bin, proxies=proxies)

        # Checking version from file
        unzip(latest_bin)
        dir_name = latest_bin.split(".")[0]
        version_from_file = get_version_from_binary(makepath(dir_name, "procexp.exe"))
        remove_tree(dir_name)

        # if not version_from_file.startswith(version) and version_from_file != '':
        if Version(version_from_file) != Version(version) and version_from_file != "":
            print("Changing version to the version number of the binary")
            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)))
        result = True
    else:
        print("Software version up-to-date (%s)" % Version(version))
    control.version = "%s-%s" % (Version(version), control.version.split("-", 1)[-1])
    # control.set_software_version(version)
    control.save_control_to_wapt()

    # Validating update-package-sources
    return result
