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

# Declaring global variables - Warnings: 1) WAPT context is only available in package functions; 2) Global variables are not persistent between calls
app_name = "SciTE"
app_dir = makepath(programfiles32, app_name)


def install():
    # Declaring local variables
    bin_name_zip = glob.glob("*Sc*.zip")[0]
    zip_extract = unzip(bin_name_zip, ".")
    extract_folder = zip_extract[0].split("\\")[1]
    bin_name = glob.glob(r"%s\*.exe" % extract_folder)[0].split("\\")[-1]
    package_version = control.get_software_version()
    app_path = makepath(app_dir, bin_name)

    # # Uninstall older SciTE version
    # for uninstall in installed_softwares("SciTE"):
    #     if not package_version in uninstall["version"]:
    #         print("Uninstall %s" % uninstall["name"])
    #         killalltasks(bin_name)
    #         cmd = uninstall_cmd(uninstall["key"])
    #         run(cmd)

    # Getting installed software version
    if isfile(app_path):
        installed_version = get_version_from_binary(app_path)
    else:
        installed_version = None

    # Installing software
    print("Installing: %s" % app_name)
    if installed_version is None or installed_version < package_version or force:
        killalltasks(control.get_impacted_process_list())
        if isdir(app_dir):
            remove_tree(app_dir)
        print("Copying: %s" % app_dir)
        copytree2(extract_folder, app_dir)

        # Creating shortcuts
        create_desktop_shortcut(app_name, app_path)
        create_programs_menu_shortcut(app_name, app_path)

        # Adding software to "list-registry"
        print("Registering %s to Windows Registry" % app_name)
        register_windows_uninstall(control, win64app=False)
        register_uninstall(app_name, icon=app_path)
        # Avoiding the usage by WAPT of the app built-in Uninstallstring
        uninstallkey.clear()

    else:
        print("%s already installed. Skipping" % app_name)


def uninstall():
    # Uninstalling software
    killalltasks(control.get_impacted_process_list())
    if isdir(app_dir):
        remove_tree(app_dir)
    unregister_uninstall(app_name)

    # Removing shortcuts
    remove_desktop_shortcut(app_name)
    remove_programs_menu_shortcut(app_name)


def audit():
    # Declaring local variables
    package_version = control.get_software_version()
    app_path = makepath(app_dir, "Scite.exe")

    # Getting installed software version
    if isfile(app_path):
        installed_version = get_version_from_binary(app_path)
    else:
        installed_version = None

    # Auditing software
    print("Auditing: %s" % control.package)
    if installed_version is None or installed_version < package_version:
        print("%s version is incorrect (%s)" % (app_name, installed_version))
        return "ERROR"
    else:
        print("%s is installed in correct version (%s)" % (app_name, installed_version))
        return "OK"
