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

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

    # Getting latest version information from WAPT API
    url = "https://wapt.tranquil.it/wapt/releases/latest/wapt_agent_list.json"
    json_load = json.loads(wgets(url, proxies=proxies))
    for a in json_load:
        if a["os_type"] == "debian_based": # Windows is not in the json but version is the same
            version = a["wapt_version"]

    # Deleting binaries
    for f in glob.glob("*.exe") + glob.glob("*.msi"):
        print("Removing: %s" % f)
        remove_file(f)
    if isdir("patchs"):
        remove_tree("patchs")
    mkdirs("patchs")

    # Downloading latest binaries
    download_url = "https://wapt.tranquil.it/wapt/releases/latest/bin/win32/waptdeploy.exe"
    latest_bin = download_url.split("/")[-1]
    print("Download URL is: %s" % download_url)
    if not isfile(latest_bin):
        print("Downloading: %s" % latest_bin)
        wget(download_url, latest_bin, proxies=proxies)
    else:
        print("Binary is present: %s" % latest_bin)
    shutil.move(latest_bin, "patchs")

    download_url = "https://wapt.tranquil.it/wapt/releases/latest/waptstarter.exe"
    latest_bin = download_url.split("/")[-1]
    print("Download URL is: %s" % download_url)
    if not isfile(latest_bin):
        print("Downloading: %s" % latest_bin)
        wget(download_url, latest_bin, proxies=proxies)
    else:
        print("Binary is present: %s" % latest_bin)

    with open("waptagent.sha256", "w") as file:
        file.write(get_sha256(latest_bin) + " " + latest_bin)

    # Checking version from file
    version_from_file = get_version_from_binary(latest_bin)
    # if not version_from_file.startswith(version) and version_from_file != '':
    if Version(version_from_file) != Version(version) and version_from_file != "":
        print("Changing version to the version number of the binary (from: %s to: %s)" % (version, version_from_file))
        # os.rename(latest_bin, latest_bin.replace(version, version_from_file))
        version = version_from_file
    else:
        print("Binary file version corresponds to online version")

    # Changing version of the package
    version = get_version_from_binary(latest_bin)
    if Version(version) > Version(control.get_software_version()):
        print("Software version updated (from: %s to: %s)" % (control.get_software_version(), Version(version)))
        package_updated = True
    else:
        print("Software version up-to-date (%s)" % Version(version))
    control.set_software_version(version)
    control.save_control_to_wapt()

    # Validating or not update-package-sources
    return package_updated
