# -*- 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":"-linux-x86_64.AppImage",
        
    }    

    url = "https://sourceforge.net/projects/scribus/files/scribus/"
    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"scribus-{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("Latest %s version is: %s" % (control.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)
    else:
        print("Binary is present: %s" % latest_bin)

    # Deleting outdated binaries
    remove_outdated_binaries(latest_bin)

    control.set_software_version(version)
    control.save_control_to_wapt()

    # Validating update-package-sources
    return package_updated