from setuphelpers import *
from setupdevhelpers import *


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

    base_url = "https://cdn.kde.org/ci-builds/utilities/kate/"
    control_mapping = {'darwin': 'macos', 'arm': 'arm64', 'x64': 'x86_64'}
    os_download_dict = {f'darwin-{control.architecture}': f'{control_mapping[control.architecture]}.dmg'}
    os_type = control.target_os + "-" + ensure_list(control.architecture)[0]

    versions = [ i.get_text(strip=True) for i in bs_find_all(base_url, "a", "href", proxies=proxies) if 'release' in i.get_text(strip=True) ]
    sorted_release = sorted(versions, key=lambda x: Version(x.split('-')[-1].strip('/')), reverse=True)

    latest_release_url = None
    for release in sorted_release:
        url = base_url + release + f"{control_mapping[control.target_os]}-{control_mapping[control.architecture]}"
        if requests.head(url).ok:
            latest_release_url = url
            version = release.split('-')[-1].strip('/')
            break

    print(f"Latest {app_name} version is: {version}")

    for i in bs_find_all(latest_release_url, "a", "href", proxies=proxies):
        bin_name = i.get_text(strip=True)
        if bin_name.endswith(os_download_dict[os_type]):
            download_url = f"{latest_release_url}/{bin_name}"

    latest_bin = download_url.rsplit('/', 1)[-1]
    latest_bin_extension = latest_bin.rsplit('.', 1)[-1]

    # Downloading latest binaries
    print(f"Download URL is: {download_url}")
    if isfile(latest_bin):
        remove_file(latest_bin)

    print(f"Downloading: {latest_bin}")
    wget(download_url, latest_bin, proxies=proxies)
    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