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

# Installation procedures:
# https://support.anydesk.com/knowledge/use-cases-for-the-command-line-interface
# https://support.anydesk.com/knowledge/command-line-interface-for-windows
# You are free to comment/uncomment `install_options` to personnalize installation

app_name = "AnyDesk"
app_dir = makepath(programfiles32, app_name)
app_path = makepath(app_dir, "AnyDesk.exe")
install_options = [
    f'--install "{app_dir}"',
    # "--start-with-win",
    "--create-shortcuts",
    "--create-desktop-icon",
    "--remove-first",
    "--silent",
    # "--update-manually",
    "--update-disabled",
    # "--update-auto",
]
app_uninstallkey = "AnyDesk"


def get_soft_version(key):
    return key["version"].split(" ")[-1]


def install():
    bin_name = glob.glob("AnyDesk*.exe")[0]
    install_exe_if_needed(
        bin_name,
        silentflags=" ".join(install_options),
        key=app_uninstallkey,
        min_version=control.get_software_version(),
        get_version=get_soft_version,
    )

    # Creating shortcuts manually since the installer is unable to...
    if "--create-shortcuts" in install_options:
        create_programs_menu_shortcut(app_name, app_path)

    if "--create-desktop-icon" in install_options:
        create_desktop_shortcut(app_name, app_path)

    # Adding QuietUninstallString
    register_uninstall(app_uninstallkey, quiet_uninstall_string='"%s" --silent --remove' % app_path)

    # Changing default start mode of the application services
    killalltasks(control.get_impacted_process_list())
    try:
        run(f'"{app_path}" --stop-service')
    except:
        time.sleep(60)
        run_notfatal(f'"{app_path}" --stop-service')
    
    # Changing default service start mode of the application
    if control.package.startswith('tis-'):
        set_service_start_mode("AnyDesk", "Manual")


def session_setup():
    remove_user_desktop_shortcut(app_name)


def uninstall():
    # Remove remaining files
    remove_desktop_shortcut(app_name)
    remove_programs_menu_shortcut(app_name)
    if isdir(app_dir):
        killalltasks(ensure_list(control.impacted_process))
        if not installed_softwares(app_uninstallkey):
            try:
                remove_tree(app_dir)
            except:
                print(f"Unable to remove: {app_dir}")
        print(f"{app_dir} remains")
