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

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

    # Search products ID
    url_api = "https://download.scenari.software/SCENARIclient/?productInfos="

    # Getting latest version information from official sources
    print("API used is: %s" % url_api)
    json_load = json.loads(wgets(url_api, proxies=proxies))

    for download in json_load["ch"]:
        # Condition to parcing binary, windows/en/.exe
        if (download.get("prc") == "dlProduct" and download.get("metas", {}).get("os") == "windows" and download.get("metas", {}).get("lang") == "en-US" and download.get("n", "").endswith(".exe")):
            url_dl = "https://download.scenari.software" + download["metas"]["path"]
            filename = download["n"]
            version = download["n"].split("client")[1].split("_")[0]
            break

    print("Version : %s" % version)
    print("Filename : %s" % filename)
    print("URL : %s" % url_dl)

    if not isfile(filename):
        package_updated = True
        wget(url_dl,filename,proxies=proxies)

    # Clean temp folders
    for f in glob.glob('*.exe'):
        if f != filename:
            remove_file(f)

    control.set_software_version(version)
    control.save_control_to_wapt()