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

import tarfile

dir_name = "nodejs"
app_dir = "/opt/nodejs"
usr_local_bin = "/usr/local/bin"


def install():
    zip_name = glob.glob("node-v*-linux-x64.tar.xz")[0]

    print(f"Extracting: {zip_name}")
    unzipped_dir = makepath(os.getcwd(), zip_name.split(".tar.xz")[0])
    if isdir(unzipped_dir):
        remove_tree(unzipped_dir)
    if isdir(dir_name):
        remove_tree(dir_name)

    with tarfile.open(zip_name, "r:xz") as tar:
        tar.extractall()

    # Renaming unzipped_dir
    print(f"Renaming: {unzipped_dir} to: {dir_name}")
    run(f"mv {unzipped_dir} {dir_name}")   # mv command in linux can be used to rename files or directories

    # Moving unzipped_dir to app_dir
    if isdir(app_dir):
        remove_tree(app_dir)
    mkdirs(app_dir)
    print(f"Moving: {dir_name} to: {app_dir}")
    move_directory(dir_name, app_dir)

    # Creating symbolic links from app_dir/bin to /usr/local/bin
    for binary in glob.glob(makepath(app_dir, "bin", "*")):
        symlink_path = makepath(usr_local_bin, binary.split("/")[-1])
        if isfile(symlink_path):
            remove_file(symlink_path)
        print(f"Creating symbolic link of: {binary} to: {usr_local_bin}")
        run(f"ln -s {binary} {symlink_path}")


def audit():
    audit_status = "OK"

    # Checking if the application directory is here
    if not isdir(app_dir) or dir_is_empty(app_dir):
        print("ERROR: Application directory is not present")
        audit_status = "ERROR"

    # Checking symbolic links located in /usr/local/bin
    symlink_list = ["node", "npm", "npx"]
    for symlink in symlink_list:
        symlink_path = makepath(usr_local_bin, symlink)
        if not os.path.islink(symlink_path):
            print(f"ERROR: Symbolic link: {symlink_path} is not present")
            audit_status = "ERROR"

    return audit_status


def uninstall():
    # Removing symbolic links located in /usr/local/bin
    for binary in glob.glob(makepath(app_dir, "bin", "*")):
        symlink_path = makepath(usr_local_bin, binary.split("/")[-1])
        if isfile(symlink_path):
            print(f"Removing symbolic link: {symlink_path}")
            remove_file(symlink_path)

    # Removing app directory
    if isdir(app_dir):
        print(f"Removing application directory: {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)
            if os.path.islink(item_path):
                shutil.move(item_path, destination)
            elif os.path.isdir(item_path):
                new_destination = os.path.join(destination, item)
                shutil.move(item_path, new_destination)

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