from setuphelpers import *
import json
import re
import requests


def update_package():
    # Declaring local variables
    package_updated = False
    proxies = get_proxies()
    if not proxies:
        proxies = get_proxies_from_wapt_console()
    app_name = control.name

    # Getting latest version from official sources
    re_versions = re.compile(r'href="docker-([\d\.]+)\.zip">')
    index = wgets("https://download.docker.com/win/static/stable/x86_64/", proxies=proxies)

    # Finding the latest version
    versions = re_versions.findall(index)
    if not versions:
        raise Exception("No versions found on Docker download page.")

    for versiondocker in sorted(versions, key=lambda p: Version(p), reverse=True):
        if control.architecture == "x64":
            latest_bin = f"docker-{versiondocker}.zip"
            download_url = f"https://download.docker.com/win/static/stable/x86_64/{latest_bin}"

        if not requests.head(download_url, proxies=proxies).status_code == 404:
            version = versiondocker
            break

    # Remove old files
    for f in glob.glob("*.zip"):
        if f != latest_bin:
            remove_file(f)

    # Downloading latest binaries
    wget(download_url, latest_bin, proxies=proxies)

    control.set_software_version(version)
    control.save_control_to_wapt()
