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

# Declaring specific app values (TO CHANGE)
package_name = "rocketchat"


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-amd64.deb"):
            url_dl_deb = download["browser_download_url"]
            break

    version = json_load["tag_name"]

    latest_bin_deb = url_dl_deb.split("/")[-1]

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

    # Downloading latest binaries
    if not isfile(latest_bin_deb):
        print("Downloading: " + latest_bin_deb)
        wget(url_dl_deb, latest_bin_deb, 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")
    else:
        print("This package is already up-to-date")

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