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


app_name = "DSInternals"
app_dir = makepath(system32(), "WindowsPowerShell", "v1.0", "Modules", app_name)


def install():
    # Declaring local variables
    package_version = control.get_software_version()
    zip_name = glob.glob(app_name + "*.zip")[0]

    print("Installing: %s (%s)" % (app_name, control.get_software_version()))
    if isdir(app_dir):
        remove_tree(app_dir)
    mkdirs(app_dir)

    # unziping archive and moving it to powershell modules folder
    print("Extracting: %s to: %s" % (zip_name, app_dir))
    unzipped_dir = zip_name.rsplit(".", 1)[0]
    unzip(zip_name, unzipped_dir)
    move_directory(makepath(unzipped_dir, app_name), app_dir)
    remove_tree(unzipped_dir)


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

    if not isdir(app_dir):
        print("%s is not installed" % app_name)
        return "ERROR"

    name = get_powershell_str("Get-Module -ListAvailable -Name %s" % app_name)
    if name != app_name:
        print("%s is not installed" % app_name)
        return "ERROR"

    version = get_powershell_str("Get-Module -ListAvailable -Name %s" % app_name, "Version")
    if Version(package_version) != Version(version):
        print("%s is installed but not up-to-date" % app_name)
        return "WARNING"

    # if everything is OK :
    print("%s (%s) is installed" % (app_name, package_version))
    return "OK"


def uninstall():
    # Uninstalling software
    if isdir(app_dir):
        remove_tree(app_dir)


def move_directory(source, destination):
    """
    Moves a directory safely, avoiding unnecessary subfolders.

    Args:
        source (str): The path of the directory to move.
        destination (str): The destination path where the directory will be moved to.

    Returns:
        bool: True if the directory was successfully moved, False otherwise.
    """
    try:
        if not os.path.exists(destination):
            os.makedirs(destination)

        for item in os.listdir(source):
            item_path = os.path.join(source, item)
            if os.path.isfile(item_path):
                shutil.move(item_path, destination)
            elif os.path.isdir(item_path):
                new_destination = os.path.join(destination, item)
                move_directory(item_path, new_destination)

        os.rmdir(source)
        return True
    except Exception as e:
        print(f"ERROR: {e}")
        return False
