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


def update_package():
    # Declaring local variables
    package_updated = False
    proxies = get_proxies()
    if not proxies:
        proxies = get_proxies_from_wapt_console()
    api_url = "https://api.github.com/repos/cryptomator/cryptomator/releases/latest"
    extensions_file = ['.dmg', '.exe', '.deb', '.rpm', '.AppImage', '.appimage', '.msi', '.zip']
    
    update_dict = {
        "os_archi":{
            "windows-x64" : ".msi",
            "darwin-x64" : "x64.dmg",
            "darwin-arm" : "arm64.dmg",
            "linux-x64" : "x86_64.AppImage",
            "linux-arm64" : "aarch64.AppImage "
        }
    }

    # Getting latest version information from official sources
    print("API used is: %s" % api_url)
    json_load = json.loads(wgets(api_url, proxies=proxies))
    for to_download in json_load["assets"]:
        if update_dict["os_archi"][f'{ensure_list(control.target_os)[0].split("(")[0]}-{ensure_list(control.architecture)[0]}'] in to_download["name"]:
            download_url = to_download["browser_download_url"]
            version = json_load["tag_name"].split("-")[-1].replace("v", "")
            latest_bin = to_download["name"]
            break

    # Downloading latest binaries
    print("Latest %s version is: %s" % (control.name, version))
    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)


    # Deleting outdated binaries
    for bin in extensions_file:
        for file in glob.glob(f"*{bin}"):
            if file != latest_bin:
                remove_file(file)

    # 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)))
        package_updated = True
    else:
        print("Software version up-to-date (%s)" % Version(version))
    control.set_software_version(version)
    control.save_control_to_wapt()

    # Validating update-package-sources
    return package_updated
