# -*- coding: utf-8 -*-
from setuphelpers 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
   
    git_repo = "freeplane/freeplane"
    url_api = f"https://api.github.com/repos/{git_repo}/releases/latest"

    print("API used is: %s" % url_api)
    json_load = wgets(url_api, proxies=proxies, as_json=True)

    version = json_load["tag_name"].strip('release-')

    download_dict = {
        'windows-x64': f'Freeplane-Setup-{version}.exe',
        'debian_based-all': f'freeplane_{version}.upstream-1_all.deb',
        'darwin-x64': f'Freeplane-{version}-intel.dmg',
        'darwin-arm': f'Freeplane-{version}-apple.dmg'
    }

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

    for download in json_load["assets"]:
        if download["name"] == download_dict[os_type]:
            download_url = download["browser_download_url"]
            latest_bin = 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
