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


def update_package():
    # Declaring local variables
    package_updated = False
    proxies = get_proxies()
    if not proxies:
        proxies = get_proxies_from_wapt_console()
        
    download_dict = {
        "windows-arm64": "-arm64.msi",
        "windows-x64": "-x64.msi",
        "windows-x86": "-x86.msi",
        "windows-all": "-x86.msi",
        "macos-x64": "-darwin-x64.tar.xz",
        "macos-arm": "-darwin-arm64.tar.xz",
        "linux-x64": "-linux-x64.tar.xz",
        "linux-arm64": "-linux-arm64.tar.xz ",
    }

    url = "https://nodejs.org/en/download"

    # Looking for last version
    print("URL used is: %s" % url)
    for bs_search in bs_find_all(url, "a", "href", proxies=proxies):
        if "nodejs.org/dist" in bs_search["href"]:
            url = bs_search["href"].rsplit("/", 1)[0]
            version = url.rsplit("/",1)[-1].replace("v","")
            break
    
    # Getting latest version information from official sources
    print("URL used is: %s" % url)
    links = bs_find_all(url,'a','href', proxies = proxies)
    to_download = download_dict[control.target_os + "-" + ensure_list(control.architecture)[0]]
    for link in links:
        if link['href'].endswith(to_download):
            download_url = url + "/" + link['href'].rsplit("/",1)[-1]
            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)

    expected_issuer = "OpenJS Foundation"
    sign_name = waptlicences.check_msi_signature(latest_bin)[0]
    if sign_name != expected_issuer:
        error(f'Bad issuer {sign_name} != {expected_issuer}')

    # 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

    # # Changing version of the package and validating update-package-sources
    # return complete_control_version(control, version)


def bs_index_of_to_dict(url, **kwargs):
    r"""Parse html "Index of" web page with BeautifulSoup and get a dict of the result

    Args:
        url (str): url of the web page to parse

    Return:
        result: a dict of the index URLs

    """
    result = {}
    for elem in bs_find_all(url, "a", "href"):
        if not "://" in elem["href"]:
            # absolute_link = urljoin(url, url + "/" + elem["href"] if not url.endswith("/") else url + elem["href"])
            absolute_link = url + "/" + elem["href"] if not url.endswith("/") else url + elem["href"]
        else:
            absolute_link = elem["href"]
        key = elem.text
        if key.endswith("..>"):  # if key.endswith("..&gt;"):
            key = elem["href"]
        result[key] = absolute_link
    return result


def is_url(x):
    try:
        result = urlparse(x)
        return all([result.scheme, result.netloc])
    except:
        return False


def bs_find_all(url, element, attribute=None, value=None, user_agent=None, proxies=None, features="html.parser", **kwargs):
    """
    Parse an HTML or XML web page with BeautifulSoup and retrieve a list of all matching results.

    Args:
        url (str): URL of the web page or string to parse.
        element (str): Searched element.
        attribute (str): Selected attribute of the element.
        value (str): Value of the selected attribute.
        user_agent (str): Specify a user-agent if needed.
        proxies (dict): Specify proxies if needed.
        features (str): BeautifulSoup feature to use.
        **kwargs: Additional parameters for the requests library.

    Returns:
        list: List of bs4.element.Tag objects representing the matching elements.

    Examples:
        >>> bs_find_all('https://www.w3.org/', 'a', 'title', 'Open Web Platform testing')[0]['href']
        'https://web-platform-tests.org/'

        >>> bs_find_all('https://www.w3.org/', 'span', 'class', 'alt-logo')[0].string
        'W3C'

    .. versionadded:: 2.0

    .. versionchanged:: 2.5
        Function can now parse string content of a page or reparse a "bs_result". It is now possible to parse a specific attribute.

    """
    url = str(url)
    if is_url(url):
        if user_agent:
            page = requests.get(url, proxies=proxies, headers={"User-Agent": user_agent}, **kwargs).text
        else:
            page = requests.get(url, proxies=proxies, **kwargs).text
    else:
        page = url
    soup = BeautifulSoup.BeautifulSoup(page, features=features)
    if value:
        return soup.find_all(element, {attribute: value})
    elif attribute:
        return soup.find_all(element, attrs={attribute: True})
    else:
        return soup.find_all(element)
