# -*- 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
    bin_name = glob.glob('mitmproxy-*.exe')[0]
    version = control.get_software_version()
    uninstall_key = f"mitmproxy {version}"
    # Installing the software
    install_exe_if_needed(bin_name,
        silentflags='--mode unattended',
        key=uninstall_key,
        min_version=version,
    )
    uninstallkey.clear()

def audit():
    # Declaring local variables
    audit_status = "OK"
    detected_apps = installed_softwares("mitmproxy")
    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():
    # Force uninstalling the software
    for to_uninstall in installed_softwares(name="mitmproxy"):
        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"]) + " --mode unattended"
            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 mitmproxy might already be partially uninstalled
            print("mitmproxy might have already been uninstalled.")
            print("Removing mitmproxy from the list of installed programs.")
            
        if uninstall_key_exists(to_uninstall["key"]):
            unregister_uninstall(to_uninstall["key"], win64app=to_uninstall["win64"])
        
        # Clean up any remaining files
        if isdir(to_uninstall["install_location"]):
            print(f"Removing remaining files in {to_uninstall['install_location']}")
            remove_tree(to_uninstall["install_location"])
    

