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


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

    # https://api.adoptium.net/q/swagger-ui/#/Assets/searchReleases
    bin_type = control.package.rsplit("-", 1)[-1]
    openjdk_version = control.get_software_version().split(".")[0]

    update_dict = {
        "windows-x64": f"https://api.adoptium.net/v3/assets/feature_releases/{openjdk_version}/ga?architecture=x64&heap_size=normal&image_type={bin_type}&jvm_impl=hotspot&os=windows",
        "windows-x86": f"https://api.adoptium.net/v3/assets/feature_releases/{openjdk_version}/ga?architecture=x86&heap_size=normal&image_type={bin_type}&jvm_impl=hotspot&os=windows",
        "mac-x64": f"https://api.adoptium.net/v3/assets/feature_releases/{openjdk_version}/ga?architecture=x64&heap_size=normal&image_type={bin_type}&jvm_impl=hotspot&os=mac",
        "mac-arm": f"https://api.adoptium.net/v3/assets/feature_releases/{openjdk_version}/ga?architecture=aarch64&heap_size=normal&image_type={bin_type}&jvm_impl=hotspot&os=mac",
        "linux-x64": f"https://api.adoptium.net/v3/assets/feature_releases/{openjdk_version}/ga?architecture=x64&heap_size=normal&image_type={bin_type}&jvm_impl=hotspot&os=linux",
        "linux-arm64": f"https://api.adoptium.net/v3/assets/feature_releases/{openjdk_version}/ga?architecture=aarch64&heap_size=normal&image_type={bin_type}&jvm_impl=hotspot&os=linux",
    }
    os_type = control.target_os + "-" + ensure_list(control.architecture)[0]

    versions = []
    bin_names = []

    api_urls = [update_dict[os_type]]
    if os_type == "windows-x64":
        api_urls.append(update_dict["windows-x86"])

    for api_url in api_urls:

        # Getting latest version information from official API
        print("API used is: %s" % api_url)
        json_load = wgets(api_url, proxies=proxies, as_json=True)[0]
        version = json_load["version_data"]["semver"].replace("+", ".")
        download_url = json_load["binaries"][0]["installer"]["link"]
        latest_bin = json_load["binaries"][0]["installer"]["name"]
        architecture = json_load["binaries"][0]['architecture']

        versions.append(version)
        bin_names.append(latest_bin)

        # Downloading latest binaries
        print(f"Latest {app_name} {architecture} 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}")
        
        expected_issuer = "Eclipse.org Foundation, Inc."
        sign_name = waptlicences.check_msi_signature(latest_bin)[0]
        if sign_name != expected_issuer:
            error(f'Bad issuer {sign_name} != {expected_issuer} ')

    version = versions[0]
    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"*.{bin_names[0].rsplit('.', 1)[-1]}"):
        if f not in bin_names:
            remove_file(f)

    control.set_software_version(version)
    control.save_control_to_wapt()

    return package_updated
