# -*- coding: utf-8 -*-
from setuphelpers import *
import os
import platform

def update_package():
    # Initializing variables
    package_updated = False
    proxies = get_proxies()
    if not proxies:
        proxies = get_proxies_from_wapt_console()

    bin_name = "SumatraPDF"
    base_url = "https://www.sumatrapdfreader.org/dl/rel/"
    dict_arch = {"x64": "-64-install.exe", "arm64": "-arm64-install.exe"}

    # Determine host architecture
    host_arch = control.architecture
    if host_arch not in dict_arch:
        raise Exception(f"Unsupported architecture: {host_arch}")

    # Getting latest version from update-check file
    version = wgets("https://www.sumatrapdfreader.org/update-check-rel.txt?lang=en&force").splitlines()[1].split()[-1]

    # Build download URL and local filename
    latest_bin = f"{bin_name}-{version}{dict_arch[host_arch]}"
    download_url = f"{base_url}{version}/{latest_bin}"

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

    # Update WAPT control
    control.set_software_version(version)
    control.save_control_to_wapt()

    return package_updated