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

app_name = "ugrep"
app_dir = makepath(programfiles, app_name)
app_path = makepath(app_dir, "ug.exe")
audit_version = False

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

def install():
    # Find the zip file
    zip_name = glob.glob(f"{app_name}*.zip")[0]
    unzip_dest = makepath(".", "temp_dezip")
    
    # Remove the temporary directory if it already exists
    if isdir(unzip_dest):
        remove_tree(unzip_dest)
    
    # Extract the zip file
    print(f"Extracting: {zip_name} to: {unzip_dest}")
    unzip(zip_name, unzip_dest)
    
    # List the contents of the temporary directory
    extracted_files = os.listdir(unzip_dest)
    print(f"Contents of the temporary directory after extraction: {extracted_files}")
    
    # Find the name of the extracted directory or the extracted files
    if not extracted_files:
        raise Exception("No extracted files or directories found")
    
    # If the first extracted item is a directory, use that directory, otherwise use unzip_dest
    first_extracted_item = makepath(unzip_dest, extracted_files[0])
    if isdir(first_extracted_item):
        unzipped_dir = first_extracted_item
    else:
        unzipped_dir = unzip_dest
    
    # Verify that the extracted directory exists
    if not isdir(unzipped_dir):
        raise Exception(f"Invalid source directory for copytree2: {unzipped_dir}")
    
    # Remove the old application directory if it exists
    if isdir(app_dir):
        remove_tree(app_dir)
    
    # Move the new extracted directory or files to the final installation directory
    copytree2(unzipped_dir, app_dir, onreplace=default_overwrite)
    
    # Remove the temporary directory
    remove_tree(unzip_dest)
    
    # Create custom shortcuts
    create_programs_menu_shortcut(app_name, target=app_path)
    
    # Get the desktop path
    desktop_path = os.path.expanduser("~\\Desktop")
    desktop_shortcut_path = makepath(desktop_path, f"{app_name}.lnk")
    
    # Create the desktop shortcut
    print(f"Creating desktop shortcut: {desktop_shortcut_path}")
    create_shortcut(desktop_shortcut_path, target=app_path)
    
    print(f"Desktop shortcut created successfully: {desktop_shortcut_path}")

def create_shortcut(shortcut_path, target):
    try:
        create_desktop_shortcut(shortcut_path, target=target)
        return True
    except Exception as e:
        print(f"Error creating shortcut: {e}")
        return False

def audit():
    # Auditing software
    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():
    # Uninstalling software
    killalltasks(ensure_list(control.impacted_process))
    if isdir(app_dir):
        remove_tree(app_dir)

    # Removing shortcuts
    desktop_path = os.path.expanduser("~\\Desktop")
    desktop_shortcut_path = makepath(desktop_path, f"{app_name}.lnk")
    
    if os.path.exists(desktop_shortcut_path):
        print(f"Removing desktop shortcut: {desktop_shortcut_path}")
        os.remove(desktop_shortcut_path)
    
    remove_programs_menu_shortcut(app_name)

    # Additional check
    if os.path.exists(desktop_shortcut_path):
        print(f"Failed to remove desktop shortcut: {desktop_shortcut_path}")
    else:
        print(f"Desktop shortcut removed successfully: {desktop_shortcut_path}")
