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


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://www.virtualbox.org/wiki/Linux_Downloads"
    distri = control.target_os.split("-")[1].lower()

    # Downloading latest binaries
    print("URL used is: %s" % url)
    for bs_search in bs_find_all(url, "a", "class", "ext-link", proxies=proxies):
        if ".deb" in str(bs_search["href"]) and distri in str(bs_search["href"]).lower():
            url_dl = bs_search["href"]
            version = url_dl.split("/")[-2]
            latest_bin = url_dl.split("/")[-1]

    url_dl_ext = "https://download.virtualbox.org/virtualbox/%s/Oracle_VirtualBox_Extension_Pack-%s.vbox-extpack" % (version,version)
    latest_bin_ext = url_dl_ext.split('/')[-1]

    print("Latest %s version is: %s" % (app_name, version))
    print("Download URL is: %s" % url_dl)
    print("Download Extension Pack URL is: %s" % url_dl_ext)

    # Downloading latest binaries
    if not isfile(latest_bin):
        print("Downloading: %s" % latest_bin)
        wget(url_dl, latest_bin.replace("~", "_"), proxies=proxies)
    else:
        print("Binary is present: %s" % latest_bin)

    # 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)))
        package_updated = True
    else:
        print("Software version up-to-date (%s)" % Version(version))
    control.set_software_version(version)
    control.save_control_to_wapt()

    # Downloading extension
    if not isfile(latest_bin_ext):
        print("Downloading: %s" % latest_bin_ext)
        wget(url_dl_ext, latest_bin_ext, proxies=proxies)
    else:
        print("Ext is present: %s" % latest_bin_ext)

    # Deleting outdated binaries
    remove_outdated_binaries(version, list_extensions=["deb", "vbox-extpack"])

    # Validating or not update-package-sources
    return package_updated
