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

app_name = "notesnook"
app_dir = makepath(programfiles, app_name)

def find_installed_path():
    # Recherche de l'emplacement de l'application installée
    for dirpath, dirnames, filenames in os.walk(app_dir):
        for filename in filenames:
            if filename == "Notesnook.exe":  
                return dirpath
    return None

def install():
    bin_name = glob.glob('*.exe')[0]
    app_path = makepath(app_dir, bin_name)
    # Installing software
    killalltasks(ensure_list(control.impacted_process))
    if isdir(app_dir) and force:
        remove_tree(app_dir)
    mkdirs(app_dir)
    filecopyto(bin_name, app_path)
    
    # Running the silent installation
    while True:
        try:
            run(f'"{app_path}" /S')
            break
        except: 
            if not params.get("install_with_luti", False):
                raise
            else:
                time.sleep(10)

    # Creating shortcuts
    installed_path = find_installed_path()
    if installed_path:
        create_desktop_shortcut(app_name, target=makepath(installed_path, "Notesnook.exe"))
        create_programs_menu_shortcut(app_name, target=makepath(installed_path, "Notesnook.exe"))
    else:
        print("Erreur: Impossible de trouver l'emplacement de l'application installée.")

def uninstall():
    # Uninstalling software
    killalltasks(ensure_list(control.impacted_process))
    for uninstall in installed_softwares('notesnook'):
        uninstall_string = uninstall.get("uninstall_string", "")
        print(f"Uninstalling notesnook: {uninstall_string}")
        run(f"{uninstall_string} --uninstall --uninstall -s")
        wait_uninstallkey_absent(uninstall['key'],max_loop=600)
    if isdir(app_dir):
        remove_tree(app_dir)

    # Removing shortcuts
    remove_desktop_shortcut(app_name)
    remove_programs_menu_shortcut(app_name)

