# -*- 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://www.python.org/downloads/windows/"
    download_dict = {
        "windows-x64": "-amd64.exe",
        "windows-arm64": "-arm64.exe",
        "windows-x86": ".exe",
        "windows-all": ".exe",
        "darwin-all": "-macos11.pkg",
    }

    # Getting latest version from official sources
    print("URL used is: %s" % url)
    for bs_search in bs_find_all(url, "a", proxies=proxies):
        if bs_search.string:
            if bs_search.string.startswith("Latest Python 3 Release"):
                version = bs_search.string.split("Python ")[-1]
    latest_bin = f'python-{version}{download_dict[control.target_os + "-" + control.architecture]}'
    download_url = f"https://www.python.org/ftp/python/{version}/{latest_bin}"

    # 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, "ProductName").split(" (")[0].split(" ")[-1]
    if Version(version_from_file, 4) != Version(version, 4) 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 version of the package
    if Version(version, 4) > Version(control.get_software_version(), 4):
        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(version, filename_contains=latest_bin)

    # Validating or not update-package-sources
    return package_updated
