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


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

    api_url = "https://api.github.com/repos/veracrypt/VeraCrypt/releases"

    download_dict = {
        "windows-x64": ".msi",
        "mac-all": ".dmg",
        "debian-bookworm-x64": "Debian-12-amd64.deb",
        "almalinux8-x64": "CentOS-8-x86_64.rpm",
    }

    os_type = control.target_os + "-" + ensure_list(control.architecture)[0]

    print("API used is: %s" % api_url)
    releases_dict = wgets(api_url, proxies=proxies, as_json=True)[:5] # Limit to 5 latest release
    valid_releases = [
        release for release in releases_dict
        if not release['prerelease']
        and not any(i in release['name'] for i in ['Windows', 'MacOSX'])
    ]
    latest_release = sorted(valid_releases, key=lambda release: Version(release['tag_name'].split("_")[-1]), reverse=True)[0]

    version = latest_release["tag_name"].split("_")[-1]
    for to_download in latest_release["assets"]:
        
        if to_download["name"].endswith(download_dict[os_type]):
            download_url = to_download["browser_download_url"]
            latest_bin = to_download["name"]
            latest_bin_extension = latest_bin.rsplit('.', 1)[-1]
            break

    # 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