# -*- coding: utf-8 -*-
##################################################
# This file is part of WAPT Enterprise
# All right reserved, (c) Tranquil IT Systems 2024
# For more information please refer to
# https://wapt.tranquil.it/store/licences.html
##################################################
from setuphelpers import *


def update_package():
    # Declaring local variables
    package_updated = False
    proxies = get_proxies()
    if not proxies:
        proxies = get_proxies_from_wapt_console()
    os_dict = {"windows": ".exe", "debian_based": ".deb", "redhat_based": ".rpm", "darwin": ".dmg"}
    api_url = "https://api.github.com/repos/gaphor/gaphor/releases/latest"

    # Get data from API
    releases_dict = json.loads(wgets(api_url, proxies=proxies))

    for asset in releases_dict["assets"]:
        if asset["browser_download_url"].endswith(".exe") and os_dict[control.target_os] in asset["browser_download_url"]:
            url_download = asset["browser_download_url"]
            latest_bin = url_download.split("/")[-1]
            version = releases_dict["tag_name"]
            break

    # Deleting binaries
    for f in glob.glob("*.exe"):
        if f != latest_bin:
            remove_file(f)

    # Downloading latest binaries
    print("Download URL is: %s" % url_download)
    if not isfile(latest_bin):
        print("Downloading: %s" % latest_bin)
        wget(url_download, latest_bin, proxies=proxies)
    else:
        print("Binary is present: %s" % latest_bin)

        # version = get_version_from_binary(latest_bin)

    control.set_software_version(version)
    control.save_control_to_wapt()
