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

r"""
{
   "key":"RustDesk",
   "name":"RustDesk",
   "version":"1.2.3.2",
   "install_date":"",
   "install_location":"C:\\Program Files\\RustDesk",
   "uninstall_string":"\"C:\\Program Files\\RustDesk\\RustDesk.exe\" --uninstall",
   "publisher":"RustDesk",
   "system_component":0,
   "win64":true
  }

"""
# Declaring global variables - Warnings: 1) WAPT context is only available in package functions; 2) Global variables are not persistent between calls


def install():
    # Declaring local variables
    bin_name = glob.glob("rustdesk-*.exe")[0]
    # Installing the software

    nb=0
    while True:
        nb=nb+1

        try:
            install_exe_if_needed(
                bin_name,
                silentflags="--silent-install",
                key="RustDesk",
                min_version=control.get_software_version(),
                timeout=60
            )
            break

        except TimeoutExpired :
            if nb == 2:
                raise
            pass

    # Clear the uninstallkeys to avoid the no-code audit and uninstall
    uninstallkey.clear()


def audit():
    # Declaring local variables
    audit_status = "OK"
    detected_apps = installed_softwares("RustDesk")
    if detected_apps:
        installed_version = detected_apps[0]["version"]
        control.name = detected_apps[0]["name"]
    else:
        installed_version = ""
        control.name = control.package.split("-", 1)[-1].replace("-", " ").title()
    audit_version = False

    # Auditing software
    if not installed_version:
        print(f"{control.name} is not installed.")
        audit_status = "ERROR"
    elif audit_version and Version(installed_version, 4) < Version(control.get_software_version(), 4):
        print(f"{control.name} ({installed_version}) installed version should be: {control.get_software_version()}")
        audit_status = "WARNING"
    else:
        print(f'{control.name} ({installed_version if not installed_version in control.name else "" }) is installed.')
        audit_status = "OK"

    return audit_status


def uninstall():
    # Uninstalling the software
    for to_uninstall in installed_softwares("RustDesk"):
        print("Removing: %s (%s)" % (to_uninstall["name"], to_uninstall["version"]))
        killalltasks(ensure_list(control.impacted_process))
        run(uninstall_cmd(to_uninstall["key"])[:2], accept_returncodes=[0, 1, 3010])
        wait_uninstallkey_absent(to_uninstall["key"])
