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


def update_package():
    print("Download/Update package content from upstream binary sources")

    # Getting proxy informations from WAPT settings
    proxy = {}
    if platform.system() == "Windows" and isfile(makepath(user_local_appdata(), "waptconsole", "waptconsole.ini")):
        proxywapt = inifile_readstring(makepath(user_local_appdata(), "waptconsole", "waptconsole.ini"), "global", "http_proxy")
        if proxywapt:
            proxy = {"http": proxywapt, "https": proxywapt}

    # Specific app values
    app_name = control.name
    git_repo = "RocketChat/Rocket.Chat.Electron"
    url_api = "https://api.github.com/repos/%s/releases/latest" % git_repo

    # Getting latest informations from Github API
    json_load = json.loads(wgets(url_api, proxies=proxy))

    for download in json_load["assets"]:
        if download["browser_download_url"].endswith("linux-x86_64.rpm"):
            url_dl_rpm = download["browser_download_url"]
            break

    version = json_load["tag_name"]

    latest_bin_rpm = url_dl_rpm.split("/")[-1]

    print("Latest " + app_name + " version is: " + version)
    print("Download url for YUM-based systems is: " + url_dl_rpm)

    if not isfile(latest_bin_rpm):
        print("Downloading: " + latest_bin_rpm)
        wget(url_dl_rpm, latest_bin_rpm, proxies=proxy)

        # Changing version of the package
        control.version = "%s-%s" % (version, int(control.version.split("-", 1)[1]) + 1)
        control.save_control_to_wapt()
        print("Changing version to " + control.version + " in WAPT\\control")
        print("Update package done. You can now build-upload your package")
    else:
        print("This package is already up-to-date")

    # Deleting outdated binaries
    for bin_in_dir in glob.glob("*.rpm"):
        if bin_in_dir != latest_bin_rpm:
            print("Outdated binary: " + bin_in_dir + " Deleted")
            remove_file(bin_in_dir)
