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


def update_package():
    # Déclaration des variables locales
    package_updated = False
    proxies = get_proxies_from_wapt_console()
    if not proxies:
        proxies = get_proxies()
    arch_dict = {
        "x64": "-x86-64-windows-binary.msi",
    }

    url = "https://sourceforge.net/projects/sbcl/files/sbcl/"
    response = requests.get(url)
    headers = bs_find_all(url, "th", "headers")

    if headers:
        first_header = headers[0]
        a_tag = first_header.find("a")
        if a_tag:
            first_link = a_tag["href"]
            version = first_link.split("/")[-2]
            print(f"First version found: {version}")

    # Trouver tous les éléments <tr> avec la classe file et le titre correspondant à la version
    requet = requests.get(url + version).text
    rows = bs_find_all(requet, "tr", class_name="file")
    target_title = f"sbcl-{version}.{arch_dict[control.architecture]}"

    # Correction du nom du fichier en évitant un point supplémentaire
    target_title = f"sbcl-{version}{arch_dict[control.architecture]}"

    download_url = f"https://sourceforge.net/projects/sbcl/files/sbcl/{version}/{target_title}"
    latest_bin = target_title
    # 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
    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))
    control.set_software_version(version)
    control.save_control_to_wapt()

    # Validating update-package-sources
    return package_updated
