# -*- coding: utf-8 -*-
from setuphelpers import *
r"""
Usable WAPT package functions: install(), uninstall(), session_setup(), audit(), update_package()
"""
# 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
    os_dict = {
        "windows": ".exe",
        "mac": ".dmg",
        "debian_based": ".deb",
        "redhat_based": ".rpm",
        "opensuse": ".rpm",
        "arch": ".pkg.tar.zst",
    }

    arch_dict = {
        "x64": "amd64",
        "amd64": "amd64",
        "arm64": "arm64",
        "arm": "arm64",
    }

    os_suffix = os_dict[control.target_os]
    arch_prefix = arch_dict[control.architecture]

    # Trouver le binaire correspondant à l'OS et l'architecture
    bin_pattern = f'Windscribe_*_{arch_prefix}{os_suffix}'
    bin_name = glob.glob(bin_pattern)[0]

    # Installing the software
    install_exe_if_needed(bin_name,
        silentflags='-silent -no-auto-start',
        key='{fa690e90-ddb0-4f0c-b3f1-136c084e5fc7}_is1',
        min_version=control.get_software_version(),
    )
    uninstallkey.clear()

def uninstall():
    # Force uninstalling the software
    for to_uninstall in installed_softwares(name="Windscribe"):
        print("Removing: %s (%s)" % (to_uninstall["name"], to_uninstall["version"]))
        killalltasks(ensure_list(control.impacted_process))

        try:
            # Adding silent flags to the uninstall command
            uninstall_command = uninstall_cmd(to_uninstall["key"]) + " /VERYSILENT /SUPPRESSMSGBOXES /NORESTART /SP-"
            run(uninstall_command)
            wait_uninstallkey_absent(to_uninstall["key"], max_loop=60)
        except Exception as e:
            print(f"Error during uninstallation: {e}")
            # Handling the case where Windscribe Director might already be partially uninstalled
            print("Windscribe Director might have already been uninstalled.")
            print("Removing Windscribe Director from the list of installed programs.")

        if uninstall_key_exists(to_uninstall["key"]):
            unregister_uninstall(to_uninstall["key"], win64app=to_uninstall["win64"])