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

app_name = "Min"
editor_dir = makepath(programfiles, "Min")
app_dir = makepath(editor_dir, "Min")
app_path = makepath(app_dir, "Min.exe")
audit_version = False

def get_installed_version(app_path):
    return get_file_properties(app_path).get("FileVersion", "")

def install():
    # Rechercher le fichier zip correspondant
    zip_name = glob.glob("Min-*.zip")
    
    if not zip_name:
        print("Error: No zip file found matching 'Min-*.zip'")
        return
    else:
        zip_name = zip_name[0]
    
    # Déterminer le nom du répertoire après extraction
    unzipped_dir = "Min"  # Répertoire temporaire pour l'extraction
    
    # Tuer les processus impactés
    killalltasks(ensure_list(control.impacted_process))
    
    # Supprimer les anciennes installations si nécessaire
    if isdir(app_dir) and force:
        remove_tree(app_dir)
    
    mkdirs(app_dir)
    
    print(f"Extracting: {zip_name} to: {unzipped_dir}")
    unzip(zip_name, unzipped_dir)
    
    # Trouver le répertoire extrait qui contient le fichier Min.exe
    extracted_path = None
    for root, dirs, files in os.walk(unzipped_dir):
        if "Min.exe" in files:
            extracted_path = root
            break
    
    if not extracted_path:
        print("Error: Min.exe not found after extraction.")
        return
    
    print(f"Copy Min from {extracted_path} to {app_dir}")
    copytree2(extracted_path, app_dir, onreplace=default_overwrite)
    
    # Création des raccourcis
    create_desktop_shortcut(app_name, target=app_path)
    create_programs_menu_shortcut(app_name, target=app_path)

def audit():
    # Audit du logiciel
    audit_status = "OK"
    installed_version = get_installed_version(app_path)
    if Version(installed_version) < Version(control.get_software_version()) and audit_version:
        print("%s is installed in version (%s) instead of (%s)" % (app_name, installed_version, control.get_software_version()))
        audit_status = "WARNING"
    elif isdir(app_dir) and not dir_is_empty(app_dir):
        print("%s (%s) is installed" % (app_name, installed_version))
        audit_status = "OK"
    else:
        print("%s is not installed" % app_name)
        audit_status = "ERROR"
    return audit_status

def uninstall():
    # Désinstallation du logiciel
    killalltasks(ensure_list(control.impacted_process))
    if isdir(app_dir):
        remove_tree(app_dir)
    if dir_is_empty(editor_dir):
        remove_tree(editor_dir)

    # Suppression des raccourcis
    remove_desktop_shortcut(app_name)
    remove_programs_menu_shortcut(app_name)
