# -*- coding: utf-8 -*-
from setuphelpers import *
from setupdevhelpers import *
import bs4 as BeautifulSoup
from urllib.parse import urlparse, urljoin
import requests


def update_package():
    # Declaring local variables
    package_updated = False
    proxies = get_proxies()
    if not proxies:
        proxies = get_proxies_from_wapt_console()

    base_url = "https://nodejs.org"
    url = "https://nodejs.org/dist/latest/"
    #latest_url = requests.head(url).headers['Location']

    download_dict = {
        "windows-arm64": "-arm64.msi",
        "windows-x64": "-x64.msi",
        "windows-x86": "-x86.msi",
        "windows-all": "-x86.msi",
        "darwin-x64": "-darwin-x64.tar.xz",
        "darwin-arm64": "-darwin-arm64.tar.xz",
        "linux-x64": "-linux-x64.tar.xz",
        "linux-arm64": "-linux-arm64.tar.xz ",
    }

    # Getting latest version information from official sources
    print("URL used is: %s" % url)
    links = bs_find_all(url,'a','href')
    to_download = download_dict[control.target_os + "-" + ensure_list(control.architecture)[0]]
    for link in links:
        if link['href'].endswith(to_download):
            download_url = base_url + link['href']
            latest_bin = link.text
            version = latest_bin.split("-")[1].replace("v", "")

    # 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)

    for f in glob.glob(f'*{to_download}'):
        if f != latest_bin:
            remove_file(f)

    # Checking version from file
    if get_os_name() == "Windows" and "windows" in control.target_os.lower():
        version_from_file = get_version_from_binary(latest_bin)
        if Version(version_from_file, 4) == Version(version, 4):
            print(f"INFO: Binary file version ({version_from_file}) corresponds to online version ({version})")
        else:
            error(f"ERROR: Binary file version ({version_from_file}) do NOT corresponds to online version ({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()

    # Validating or not update-package-sources
    return package_updated

