# -*- 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()
    url = "https://openvpn.net/community-downloads/"
    arch_dict = {"x64": "amd64", "x86": "x86"}

    # Getting latest version from official sources
    print("URL used is: %s" % url)
    for bs_search in bs_find_all(url, "a", "class", "ovpn-button", proxies=proxies):
        if (not "alpha" in bs_search["href"]) and arch_dict[control.architecture] in bs_search["href"]:
            latest_bin = bs_search["href"].split("/")[-1]
            version = latest_bin.split("-")[1]
            download_url = bs_search["href"]
            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)
    # 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 (from: %s to: %s)" % (version, version_from_file))
        # os.rename(latest_bin, latest_bin.replace(version, version_from_file))
        version = version_from_file
    else:
        print("Binary file version corresponds to online version")

    # Changing name of the package
    # OpenVPN 2.6.0-I004 amd64 (2.6.009)
    control.name = get_msi_properties(latest_bin)["ProductName"] + " (%s)" % get_msi_properties(latest_bin)["ProductVersion"]

    # 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
    remove_outdated_binaries(latest_bin.split("-")[1], filename_contains=latest_bin.split("-")[3])

    # Validating or not update-package-sources
    return package_updated
