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


def update_package():
    # Declaring local variables
    result = False
    proxies = get_proxies()
    if not proxies:
        proxies = get_proxies_from_wapt_console()
    app_name = control.name
    arch = control.architecture
    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 = json.loads(wgets(api_url, proxies=proxies))
    version = json_load["tag_name"]
    download_url = f"https://update.code.visualstudio.com/{version}/linux-deb-x64/stable"
    latest_bin = f"code_{version}_{arch}.deb"

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

    # Downloading latest binaries
    if not isfile(latest_bin):
        print("Downloading: %s" % latest_bin)
        wget(download_url, 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
    else:
        print("Software version up-to-date (%s)" % Version(version))
    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
