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


def update_package():
    import bs4 as BeautifulSoup
    import requests, re
    from waptpackage import PackageEntry

    # Declaring specific app values
    bin_name_string = "nvda_%s.exe"
    bin_name_joker = "nvda_*.exe"

    app_name = control["name"]
    url = "https://www.nvaccess.org/download/"

    # Get Proxy informations from WAPT settings
    proxies = {}
    if isfile(makepath(application_data(), "waptconsole", "waptconsole.ini")):
        proxywapt = inifile_readstring(makepath(user_local_appdata(), "waptconsole", "waptconsole.ini"), "global", "http_proxy")
        if proxywapt:
            proxies = {"http": proxywapt, "https": proxywapt}

    verify = True
    pe = PackageEntry()
    pe.load_control_from_wapt(os.getcwd())
    current_version = pe["version"].split("-", 1)[0]
    verify = True

    # Get latest version number from official website
    page = requests.get(url, headers={"User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64)"}, verify=verify).text
    bs = BeautifulSoup.BeautifulSoup(page)

    bs_raw_string = str(bs.find("div", {"class": "download-version__details section-title-v2"}).find("h2").text)

    version = re.sub("[^0123456789\.]", "", bs_raw_string).strip()

    print("Latest " + app_name + " version is: " + version)

    url_dl = url + "nvda/releases/" + version + "/nvda_%s.exe" % version
    print("Download url is: " + url_dl)

    latest_bin = bin_name_string % version

    # Deleting outdated binaries
    for actual_bin in glob.glob(bin_name_joker):
        if actual_bin != latest_bin:
            print(actual_bin + " Deleted")
            remove_file(actual_bin)

    # Downloading latest binaires
    if not isfile(latest_bin):
        print("Downloading " + url_dl)
        wget(url_dl, latest_bin, proxies=proxies)
    version_from_file = get_file_properties(latest_bin)["FileVersion"]
    # if not version_from_file.startswith(version) and version_from_file != "":
    if Version(version_from_file) != Version(version) and version_from_file != "":
        print("Changing version to the version number of the binary (from: %s to: %s)" % (version, version_from_file))
        os.rename(latest_bin, latest_bin.replace(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) > Version(control.get_software_version()):
        print("Software version updated (from: %s to: %s)" % (control.get_software_version(), Version(version)))
    else:
        print("Software version up-to-date (%s)" % Version(version))
    control.version = "%s-%s" % (Version(version), control.version.split("-", 1)[-1])
    # control.set_software_version(version)
    control.save_control_to_wapt()
