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


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

    #url_base = "https://learn.microsoft.com/en-us/azure/virtual-desktop/whats-new-client-windows?pivots=remote-desktop-msi"
    url_base = "https://learn.microsoft.com/en-us/previous-versions/remote-desktop-client/whats-new-windows?tabs=windows-msrdc-msi"

    table = bs_find_all(url_base, "table", proxies=proxies)
    rows = bs_find(table, "tbody").find_all('tr')

    for row in rows:
        tds = row.find_all("td")
        release_type = tds[0].text
        # If is the Public Windows 64-bit release
        if release_type == "Public":
            microsoft_url = next((a["href"] for a in tds[2].find_all("a") if "Windows 64-bit" in a.text), None)

    download_url = requests.head(microsoft_url, proxies=proxies).headers['Location']
    latest_bin = download_url.rsplit('/', 1)[-1]
    latest_bin_extension = latest_bin.rsplit('.', 1)[-1]
    version = latest_bin.split('_')[1]

    # Downloading latest binaries
    print(f"Latest {app_name} version is: {version}")
    print(f"Download URL is: {download_url}")
    if not isfile(latest_bin):
        print(f"Downloading: {latest_bin}")
        wget(download_url, latest_bin, proxies=proxies)
    else:
        print(f"Binary is present: {latest_bin}")

    # Changing version of the package
    if Version(version) > Version(control.get_software_version()):
        print(f"Software version updated (from: {control.get_software_version()} to: {Version(version)})")
        package_updated = True
    else:
        print(f"Software version up-to-date ({Version(version)})")

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

    control.set_software_version(version)
    control.save_control_to_wapt()

    return package_updated