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

r"""
Usable WAPT package functions: install(), uninstall(), session_setup(), audit(), update_package()

"""

def install():
    # Déclaration des variables locales
    try:
        bin_name = glob.glob('Vivaldi.*.exe')[0]
    except IndexError:
        raise Exception("No Vivaldi installer found in the current directory")

    # Installation du logiciel
    install_exe_if_needed(bin_name,
                          silentflags='--vivaldi-silent --do-not-launch-chrome --system-level',
                          key='Vivaldi',
                          min_version=control.get_software_version(),
                          accept_returncodes=[0, 3010, 1641])
    
    # Nettoyer les clés de désinstallation pour éviter les audits sans code
    uninstallkey.clear()

def uninstall():
    for uninstall in installed_softwares('vivaldi'):
        uninstall_string = uninstall.get("uninstall_string", "")
        if uninstall_string:
            print(f"Uninstalling Vivaldi: {uninstall_string}")
            try:
                # Exécution de la commande de désinstallation avec gestion des erreurs
                run(f"{uninstall_string} --uninstall --force-uninstall --vivaldi --system-level", accept_returncodes=[0, 19])
                wait_uninstallkey_absent(uninstall['key'], max_loop=600)
            except CalledProcessErrorOutput as e:
                print(f"Error uninstalling Vivaldi: {e.output}")
                if 'Could not get application shortcuts location' in e.output:
                    print("Ignoring error related to application shortcuts location.")
                else:
                    raise
        else:
            print("No uninstall string found for Vivaldi")

def audit():
    if not uninstall_key_exists("Vivaldi"):
        print('uninstallkey Vivaldi not found')
        return "ERROR"
    else:
        return "OK"
