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

def update_package():
    # Declaring local variables
    package_updated = False

    proxies = get_proxies_from_wapt_console()
    if not proxies:
        proxies = get_proxies()

    user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:128.0) Gecko/20100101 Firefox/128.0"
    data = requests.head('https://cdn1.waterfox.net/waterfox/releases/latest/windows',allow_redirects=True,proxies=proxies)
    download_url = data.url

    api_url = "https://api.github.com/repos/BrowserWorks/Waterfox/releases/latest"

    releases_dict = json.loads(wgets(api_url, proxies=proxies))
    latest_bin = "Waterfox Setup " + releases_dict["tag_name"] + ".exe"
    version = releases_dict["tag_name"]

    # 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, user_agent=user_agent)
        package_updated = True
    else:
        print("Binary is present: %s" % latest_bin)


    # Deleting outdated binaries
    for f in glob.glob('*.exe'):
        if f != latest_bin:
            remove_file(f)



    # Mettre à jour le package
    control.set_software_version(version)
    control.save_control_to_wapt()


