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

# Declaring global variables - Warnings: 1) WAPT context is only available in package functions; 2) Global variables are not persistent between calls


def update_package():
    result = False
    proxies = get_proxies()

    if not proxies:
        proxies = get_proxies_from_wapt_console()

    git_repo = "neovim/neovim"
    url_api = "https://api.github.com/repos/%s/releases/latest" % git_repo

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

    for download in json_load["assets"]:
        if download["name"].endswith('.msi') :
            url_dl = download["browser_download_url"]
            version = json_load["tag_name"].replace("v", "")
            latest_bin = download["name"]
            break


    for f in glob.glob('*.msi'):
        if get_version_from_binary(f) < version :
            remove_file(f)

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

        # Checking version from file
        version = get_version_from_binary(latest_bin)

    # 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(version))
        control.save_control_to_wapt()

    # Validating update-package-sources
    return result
