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


def update_package():
    import re, requests, glob

    proxies = {}
    if isfile(makepath(user_local_appdata(), "waptconsole", "waptconsole.ini")):
        proxywapt = inifile_readstring(makepath(user_local_appdata(), "waptconsole", "waptconsole.ini"), "global", "http_proxy")
        if proxywapt:
            proxies = {"http": proxywapt, "https": proxywapt}

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

    url = requests.head("https://download.mozilla.org/?product=thunderbird-latest&os=linux64&lang=%s" % (lang), proxies=proxies).headers["Location"]
    url = url.replace('.tar.xz','.tar.xz')

    filename = url.rsplit("/", 1)[1].replace("%20", " ")


    version = filename.split("-")[1].split('.tar')[-2]
    datajson = json.loads(wgets("https://product-details.mozilla.org/1.0/thunderbird_versions.json", proxies=proxies))
    version_from_api = datajson.get("LATEST_THUNDERBIRD_VERSION_NEXT", "")
    if not version_from_api:
        version_from_api = datajson["LATEST_THUNDERBIRD_VERSION"]


    url = url.replace(version, version_from_api)
    version = version_from_api
    filename = url.rsplit("/", 1)[1].replace("%20", "_")

    if not isfile(filename):
        print("Downloading %s from %s" % (filename, url))
        wget(url, filename, proxies=proxies)
    else:
        print(filename + " already exist")

    # updates control version from filename, increment package version.
    control.set_software_version(version.replace('esr',''))
    control.save_control_to_wapt()

    # removes old exe
    if isfile(filename):
        exes = glob.glob("*.tar.gz")
        for fn in exes:
            if fn != filename:
                print("Delete " + fn)
                remove_file(fn)

    print("The update is complete, you can now test and then launch a build upload.")