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


def update_package():
    # Declaring local variables
    package_updated = False
    proxies = get_proxies()
    if not proxies:
        proxies = get_proxies_from_wapt_console()
    app_name = control.name
    url = "https://sourceforge.net/projects/crystaldiskinfo/files/"


    # Getting latest version from download url
    print("URL latest version from download url")
    for bs_search in bs_find_all(url, "tr", "class", proxies=proxies) :
        version = bs_search["title"]
        break
    url_version = url + version

    for bs_search in bs_find_all(url_version, "tr", "title", proxies=proxies) :
        p = re.compile(r'\D{1,}\d{1,}[_]\d{1,}[_]\d{1,}[.]\bexe\b')
        result = re.search(p,bs_search["title"])
        if result: 
            download_url = bs_search.find_next("a").get("href")
            latest_bin = download_url.split("/")[-2]
            break

    # Downloading latest binaries
    print("Latest %s version is: %s" % (app_name, 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)

    # Checking version from file
    version_from_file = get_version_from_binary(latest_bin)
    if Version(version_from_file, 4) != Version(version, 4) and version_from_file != "":
        print("Changing version to the version number of the binary (from: %s to: %s)" % (version, version_from_file))
        version = version_from_file
    else:
        print("Binary file version corresponds to online version")

    # Changing version of the package
    if Version(version, 4) > Version(control.get_software_version(), 4):
        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))

    # 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()

    # Validating or not update-package-sources
    return package_updated
