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


def update_package():
    # Declaring local variables
    package_updated = False
    proxies = get_proxies()
    if not proxies:
        proxies = get_proxies_from_wapt_console()
    update_dict = {
        "download_url": {
            "windows-x86": "https://desktop-release.canva.com/windows-enterprise/Canva Setup Latest x86.msix",
            "windows-x64": "https://desktop-release.canva.com/windows-enterprise/Canva Setup Latest x64.msix",
        },
    }
    download_url = update_dict["download_url"][f'{ensure_list(control.target_os)[0].split("(")[0]}-{ensure_list(control.architecture)[0]}']
    latest_bin = download_url.split("/")[-1]

    # Deleting all binaries
    remove_outdated_binaries("*", "msix")

    # 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)

    # Checking version from file
    if get_os_name() == "Windows" and "windows" in control.target_os.lower():
        version_bin = unzip(latest_bin, ".", r"app\Canva.exe", False)[0]
        version = get_version_from_binary(version_bin)
        remove_file(version_bin)
    else:
        version = control.get_software_version()

    # 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)
