# -*- coding: utf-8 -*-
from setuphelpers import *
from setupdevhelpers 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://download.nomachine.com/download/?id=7&platform=mac"

    user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36'
    headers = { 'user-agent': user_agent}
    requests_session = requests.Session()
    requests_session.headers.update({'user-agent': user_agent })
    result = requests_session.get(url).content

    # Getting latest version from official sources
    print("URL used is: %s" % url)
    for bs_search in bs_find_all(requests_session.get(url).content, "a", proxies=proxies):
        if ".dmg" in bs_search.get("href", ""):
            download_url = bs_search["href"]
            latest_bin = bs_search["href"].rsplit("/", 1)[-1]
            latest_bin_extension = latest_bin.rsplit(".", 1)[-1]
            version = latest_bin.split("_")[1]
            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)
        package_updated = True
    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()

    for f in glob.glob(f'*.{latest_bin_extension}'):
        if f != latest_bin:
            remove_file(f)

    # Validating or not update-package-sources
    return package_updated
