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

app_name = "PHP"
app_dir = makepath(programfiles, app_name)
app_path = makepath(app_dir, "php.exe")
icon_path = app_path
audit_version_number = False


def get_installed_version(uninstallkey):
    for soft in installed_softwares(uninstallkey=uninstallkey):
        return soft.get("version", None)
    return None


def install():
    # Declaring local variables
    package_version = control.get_software_version()
    installed_version = get_installed_version(app_name)
    bin_name = glob.glob("php-*.zip")[0]

    # Installing software
    print("Installing: %s" % app_name)
    if installed_version is None or Version(installed_version) < Version(package_version) or force:
        killalltasks(control.get_impacted_process_list())
        if isdir(app_dir):
            remove_tree(app_dir)
        mkdirs(app_dir)
        print("Extracting: %s to: %s" % (bin_name, app_dir))
        unzip(bin_name, target=app_dir)
        add_to_system_path(app_dir)

        # Creating shortcuts
        if not params.get("remove_desktop_shortcut"):
            create_desktop_shortcut(app_name, app_path, icon=icon_path)
            create_programs_menu_shortcut(app_name, app_path, icon=icon_path)

        # Adding software to "list-registry"
        print("Registering: %s to Windows Registry" % app_name)
        register_windows_uninstall(control, win64app=iswin64())
        register_uninstall(app_name, win64app=iswin64(), icon=icon_path)
    else:
        print("%s is already installed and up-to-date" % app_name)


def audit():
    # Declaring local variables
    package_version = control.get_software_version()
    installed_version = get_installed_version(app_name)

    # Auditing software
    print("Auditing: %s" % control.package)
    if installed_version is None:
        print("%s is not installed" % app_name)
        return "ERROR"
    elif Version(installed_version) != Version(package_version) and audit_version_number:
        print("%s is installed in version (%s) instead of (%s)" % (app_name, installed_version, package_version))
        return "WARNING"
    else:
        print("%s (%s) is installed" % (app_name, installed_version))
        return "OK"


def uninstall():
    # Uninstalling software
    killalltasks(control.get_impacted_process_list())
    if isdir(app_dir):
        remove_tree(app_dir)
    unregister_uninstall(app_name, win64app=iswin64())
    remove_from_system_path(app_dir)

    # Removing shortcuts
    remove_desktop_shortcut(app_name)
    remove_programs_menu_shortcut(app_name)
