# -*- coding: utf-8 -*-
from setuphelpers import *
import requests
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

    os_dict = {
        "windows-x64": "win32-x64",
        "windows-arm": "win32-arm64",
        "redhat_based-x64": "linux-rpm-x64",
        "debian(>=12),ubuntu(>=20)-x64": "linux-deb-x64",
        "debian(>=12),ubuntu(>=20)-arm64": "linux-deb-arm64",
        "darwin-x64": "darwin",
        "darwin-arm": "darwin-arm64",
    }

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

    api_url = "https://api.github.com/repos/microsoft/vscode/releases/latest"

    # Getting latest version information from official sources
    print("API used is: %s" % api_url)
    json_load = wgets(api_url, proxies=proxies, as_json=True)
    version = json_load["tag_name"]
    download_url = f"https://update.code.visualstudio.com/{version}/{os_dict[os_type]}/stable"
    download_url = requests.head(download_url, proxies=proxies).headers['Location']
    latest_bin = download_url.rsplit('/', 1)[-1]
    latest_bin_extension = latest_bin.rsplit('.', 1)[-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}")

    expected_issuer = "Microsoft Corporation"
    sign_name = waptlicences.check_exe_signing_certificate(latest_bin)[0]
    if sign_name != expected_issuer:
        error(f'Bad issuer {sign_name} != {expected_issuer} ')

    # 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

