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


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

    download_dict = {
        "windows-x64": "https://dl.teamviewer.com/download/TeamViewer_Host_Setup_x64.exe",
        "windows-x86": "https://dl.teamviewer.com/download/TeamViewer_Host_Setup.exe",
        "darwin-all": "https://dl.teamviewer.com/download/version_15x/TeamViewerHost.dmg?ref=https%3A%2F%2Fwww.teamviewer.com%2Ffr%2Fdownload%2Fportal%2Fmacos%2F",
    }
    download_url = download_dict[control.target_os + "-" + ensure_list(control.architecture)[0]]
    latest_bin = download_url.split("/")[-1]
    latest_bin_extension = latest_bin.rsplit(".", 1)[-1]
    version = wgets("https://download.teamviewer.com/download/update/TVVersion15.txt").strip()

    # Downloading latest binaries
    print(f"Latest {app_name} version is: {version}")
    print(f"Download URL is: {download_url}")
    if not isfile(latest_bin):
        print(f"Downloading: {latest_bin}")
        wget(download_url, latest_bin, proxies=proxies)
    else:
        print(f"Binary is present: {latest_bin}")

    expected_issuer = "TeamViewer Germany GmbH"
    sign_name = waptlicences.check_exe_signing_certificate(latest_bin)[0]
    if sign_name != expected_issuer:
        error(f'Bad issuer {sign_name} != {expected_issuer} ')

    # Changing version of the package
    if Version(version) > Version(control.get_software_version()):
        print(f"Software version updated (from: {control.get_software_version()} to: {Version(version)})")
        package_updated = True
    else:
        print(f"Software version up-to-date ({Version(version)})")

    for f in glob.glob(f'*.{latest_bin_extension}'):
        if f != latest_bin:
            remove_file(f)

    control.set_software_version(get_version_from_binary(latest_bin))
    control.save_control_to_wapt()

    return package_updated
