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


def update_package():
    # Initializing variables
    bin_name_sub = "Zotero-%s_setup.exe"
    proxies = get_proxies()
    if not proxies:
        proxies = get_proxies_from_wapt_console()
    app_name = control.name
    url = "https://www.zotero.org/download/"

    # Getting latest version from official sources
    print("URL used is: %s" % url)
    for bs_search in bs_find_all(url, "script", "type", "text/javascript", proxies=proxies):
        temp_str = str(bs_search)
        if "win32" in temp_str:
            dict_version = json.loads(temp_str.split(":", 1)[-1].split("\n", 1)[0].split("}")[0] + "}")
            version = dict_version["win32"]
            latest_bin = bin_name_sub % version
            url_dl = "https://www.zotero.org/download/client/dl?channel=release&platform=win32&version=%s" % version
            break

    print("Latest %s version is: %s" % (app_name, version))
    print("Download url is: %s" % url_dl)

    # Downloading latest binaries
    if not isfile(latest_bin):
        print("Downloading: %s" % latest_bin)
        wget(url_dl, latest_bin, proxies=proxies)

    # Changing version of the package
    control.version = "%s-%s" % (version, control.version.split("-", 1)[-1])
    control.save_control_to_wapt()

    # Deleting outdated binaries
    remove_outdated_binaries(version)
