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

bin_name_sub = "DriverStoreExplorer.v%s.zip"


def update_package():
    # Initializing variables
    proxies = get_proxies()
    if not proxies:
        proxies = get_proxies_from_wapt_console()
    app_name = control.name
    git_repo = "lostindark/DriverStoreExplorer"
    url_api = "https://api.github.com/repos/%s/releases/latest" % git_repo
    bin_start = bin_name_sub.split("%s")[0]

    # Getting latest version 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"].startswith(bin_start):
            url_dl = download["browser_download_url"]
            break

    version = json_load["tag_name"].replace("v", "")
    latest_bin = bin_name_sub % version

    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
        control.version = "%s-%s" % (version, control.version.split("-", 1)[-1])
        control.save_control_to_wapt()
        print("Changing package version to: %s in WAPT\\control" % control.version)

    # Deleting outdated binaries
    remove_outdated_binaries(version)
