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


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

    url_base = "https://www.charlesproxy.com/latest-release/"
    
    version = bs_find(url_base,"input", "name", "version", proxies=proxies)['value'].replace('v', '')
    
    download_dict = {
        "windows-x64": f"https://www.charlesproxy.com/assets/release/{version}/charles-proxy-{version}-win-x86_64.msi",
        "darwin-x64" :f"https://www.charlesproxy.com/assets/release/{version}/charles-proxy-{version}.dmg",
        "linux-x64" : f"https://www.charlesproxy.com/assets/release/{version}/charles-proxy-{version}_amd64.tar.gz"
    }
    
    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]

    # 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 = 'XK72 Limited'
    sign_name = waptlicences.check_msi_signature(latest_bin)[0]
    if sign_name != expected_issuer:
        error(f'Bad issuer {sign_name} != {expected_issuer} ')

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

    # 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})")
        package_updated = True
    else:
        print(f"Software version up-to-date ({version})")

    control.set_software_version(version)
    control.save_control_to_wapt()

    # Validating or not update-package-sources
    return package_updated