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

def update_package():
    package_updated = False
    proxies = get_proxies()
    if not proxies:
        proxies = get_proxies_from_wapt_console()
    source_html = wgets('https://thorium.edrlab.org/en',proxies=proxies).splitlines()
    for line in source_html:
        if 'https://github.com/edrlab/thorium-reader/releases/download' in line:
            version = line.split('/')[-2].replace('v','')
            break
    latest_bin = f'Thorium.Setup.{version}.exe'
    download_url = f'https://github.com/edrlab/thorium-reader/releases/download/v{version}/Thorium.Setup.{version}.exe'

    # Deleting binaries
    for f in glob.glob("*.exe") + glob.glob("*.msi"):
        print("Removing: %s" % f)
        remove_file(f)

    # Downloading latest binaries
    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
    version = get_version_from_binary(latest_bin, "ProductVersion")
    if Version(version) > Version(control.get_software_version()):
        print("Software version updated (from: %s to: %s)" % (control.get_software_version(), Version(version)))
        package_updated = True
    else:
        print("Software version up-to-date (%s)" % Version(version))
    control.set_software_version(version)
    control.save_control_to_wapt()

    # Validating or not update-package-sources
    return package_updated