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

def update_package():
    # Initializing variables
    proxies = get_proxies()
    if not proxies:
        proxies = get_proxies_from_wapt_console()

    #url = "https://jrsoftware.org/isdl.php"
    url = "https://api.github.com/repos/jrsoftware/issrc/releases/latest"

    # Getting latest version from official sources
    print("URL used is: %s" % url)

    # Parsing GitHub API
    releases_dict = json.loads(wgets(url, proxies=proxies))
    assets = releases_dict["assets"]

    for asset in assets:
        if asset["browser_download_url"].endswith("x86.exe"):
            url_download = asset["browser_download_url"]
            latest_bin = url_download.split("/")[-1]
            version = releases_dict["name"].split(" ")[-1]
            break

    print("Latest %s version is: %s" % (control.name, version))
    print("Download url is: %s" % url_download)

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

    # Changing version of the package
    control.set_software_version(version)
    control.save_control_to_wapt()
    print("Changing package version to: %s in WAPT\\control" % control.version)

    # Deleting outdated binaries
    remove_outdated_binaries(version)