# -*- coding: UTF-8 -*-
from setuphelpers import *
import requests
import json
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
    arch = {"x64,arm64": "win64", "x86": "win"}

    # Downloading
    lang = control.locale
    # Translating locale
    if "en" in lang:
        lang = "en-US"
    if "es" in lang:
        lang = "es-ES"

    download_url = requests.head(
        "https://download.mozilla.org/?product=thunderbird-latest&os=%s&lang=%s" % (arch[control.architecture], lang), proxies=proxies
    ).headers["Location"]
    latest_bin = download_url.rsplit("/", 1)[1].replace("%20", "_")
    version = download_url.split("/")[-4]

    datajson = json.loads(wgets("https://product-details.mozilla.org/1.0/thunderbird_versions.json", proxies=proxies))
    version_from_api = datajson.get("THUNDERBIRD_ESR_NEXT", "")
    if not version_from_api:
        version_from_api = datajson["THUNDERBIRD_ESR"]

    download_url = download_url.replace(version, version_from_api)
    version = version_from_api.replace('esr','')
    latest_bin = download_url.rsplit("/", 1)[1].replace("%20", "_")
    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 = 'Mozilla Corporation'
    sign_name = waptlicences.check_msi_signature(latest_bin)[0]
    if sign_name != expected_issuer:
        error('Bad issuer %s != %s ' % (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(version)
    control.save_control_to_wapt()

    return package_updated
