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

bin_contains = ".exe"

def update_package():
    # Declaring local variables
    result = False
    proxies = get_proxies()
    if not proxies:
        proxies = get_proxies_from_wapt_console()
    app_name = control.name
    git_repo = "ImageMagick/ImageMagick"
    url_api = "https://api.github.com/repos/%s/releases/latest" % git_repo
    if control.architecture == "x64":
        arch = "-x64-dll"
    elif control.architecture == "arm":
        arch = "-arm64-dll"
    else:
        arch = "-x86-dll"

    # Getting latest version information from official sources
    print(f"API used is: {url_api}")
    json_load = json.loads(wgets(url_api, proxies=proxies))

    for download in json_load["assets"]:
        if download["name"].endswith(bin_contains) and arch in download["name"]:
            url_dl = download["browser_download_url"]
            version = json_load["tag_name"].replace("-", ".")
            latest_bin = download["name"]
            break

    print("Latest %s version is: %s" % (app_name, version))
    print("Download URL is: %s" % url_dl)

    # Downloading latest binaries
    if not isfile(latest_bin):
        print("Downloading: %s" % latest_bin)
        wget(url_dl, latest_bin, proxies=proxies)

    # Changing version of the package
    if Version(version) > Version(control.get_software_version()):
        print("Software version updated (from: %s to: %s)" % (control.get_software_version(), Version(version)))
        result = True
    control.version = "%s-%s" % (Version(version), control.version.split("-", 1)[-1])
    # control.set_software_version(version)
    control.save_control_to_wapt()

    # Deleting outdated binaries
    remove_outdated_binaries(version)

    # Validating update-package-sources
    return result