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

def update_package():
    proxies = {}
    if isfile(makepath(user_local_appdata(), "waptconsole", "waptconsole.ini")):
        proxywapt = inifile_readstring(makepath(user_local_appdata(), "waptconsole", "waptconsole.ini"), "global", "http_proxy")
        if proxywapt:
            proxies = {"http": proxywapt, "https": proxywapt}

    currentpath = os.path.dirname(os.path.realpath(__file__))

    url = "https://linuxecke.volkoh.de/vokoscreen/vokoscreen-download.html"

    # Getting latest version information from official sources
    print("API used is: %s" % url)
    for bs_search in bs_find_all(url,"tr", proxies = proxies):
        if bs_search.find_next("a")["href"]:
            download_url = "https://linuxecke.volkoh.de/vokoscreen/" + bs_search.find_next("a")["href"]
            latest_bin = bs_search.find_next("a")["href"].split("/")[-1]
            version = latest_bin.split("-")[1]
            break

    # Downloading latest binaries
    print(f"Latest version of {control.name} is: {version}")
    print("Download URL is: %s" % download_url)
    if not isfile(latest_bin):
        print("Downloading: %s" % latest_bin)
        wget(download_url, latest_bin, proxies=proxies)
    else:
        print("Binary is present: %s" % latest_bin)

    # Changing version of the package
    if Version(version) > Version(control.get_software_version()):
        print(f"Software version updated (from: {control.get_software_version()} to: {Version(version)})")
        package_updated = True
    else:
        print(f"Software version up-to-date ({Version(version)})")

    # Deleting binaries
    for f in glob.glob("*.exe"):
        if f != latest_bin:
            remove_file(f)
    
    control.set_software_version(version)
    control.save_control_to_wapt()

    return package_updated