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


def update_package():
    # Declaring local variables
    result = False
    proxies = get_proxies()
    if not proxies:
        proxies = get_proxies_from_wapt_console()
    app_name = control.name
    api_url = "https://sourceforge.net/projects/docfetcher/best_release.json"
    bin_contains = "DocFetcher-"

    # Getting latest version information from official sources
    print("API used is: %s" % api_url)
    json_load = json.loads(wgets(api_url, proxies=proxies))
    for download in json_load["platform_releases"]:
        latest_bin = json_load["platform_releases"][download]["filename"].split("/")[-1]
        if bin_contains in latest_bin and latest_bin.endswith(".exe"):
            if "RC" in latest_bin:
                error("ERROR: Don't release RC version or found a workaround with the version number")
            download_url = json_load["platform_releases"][download]["url"]
            version = latest_bin.split("-")[1]
            break

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

        # Checking version from file
        version_from_file = get_version_from_binary(latest_bin)
        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, bin_contains + version_from_file + bin_ends)
            version = version_from_file
        else:
            print("Binary file version corresponds to online version")

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

    # Deleting outdated binaries
    remove_outdated_binaries(version)

    # Validating update-package-sources
    return result