# -*- 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()
    user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:128.0) Gecko/20100101 Firefox/128.0"
    if not proxies:
        proxies = get_proxies()
    arch_dict = {
        "x64":"-Setup.exe",

    }

    url = "https://sourceforge.net/projects/pwgen-win/files/Password%20Tech/"
    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"PwTech-{version}{arch_dict[control.architecture]}"
    download_link = None
    for row in rows:
        if row.get('title') == target_title:
            a_tag = row.find("a", title=f"Click to download {target_title}")
            if a_tag:
                download_link = a_tag['href']
                break
    if download_link:
        print(f"Download link found: {download_link}")


    latest_bin = target_title
    download_url = download_link





    # 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

    # # Changing version of the package and validating update-package-sources
    # return complete_control_version(control, version)
