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

ext_uid_name = "ms-python.python"


def install():
    # Initializing variables
    package_version = control.get_software_version()
    ext_file_name = glob.glob("*%s*.vsix" % ext_uid_name)[0]
    if get_os_name() == "Windows":
        app_dir = makepath(programfiles, "Microsoft VS Code")
        app_bin_path = makepath(app_dir, "bin", "code")
    elif get_os_name() == "Linux":
        app_dir = makepath("/", "usr", "share", "code")
        app_bin_path = makepath(app_dir, "bin", "code")
    elif get_os_name() == "Darwin":
        app_dir = makepath("/", "Applications", "Visual Studio Code.app")
        app_bin_path = makepath(app_dir, "Contents", "Resources", "app", "bin", "code")
    ext_path = makepath(app_dir, ext_file_name)

    # Removing old extensions from app_dir
    for ext in glob.glob(makepath(app_dir, "*%s*.vsix" % ext_uid_name)) + [makepath(app_dir, "ms-python-release.vsix")]:
        print("Removing: %s" % ext)
        remove_file(ext)

    # Copying extension to app_dir
    print("Copying: %s to: %s" % (ext_file_name, app_dir))
    filecopyto(ext_file_name, app_dir)

    # Disable File Validation Warning
    if get_os_name() == "Windows":
        set_environ_variable("PYDEVD_DISABLE_FILE_VALIDATION", "1")


def session_setup():
    # Initializing variables
    package_version = control.get_software_version()
    if get_os_name() == "Windows":
        app_dir = makepath(programfiles, "Microsoft VS Code")
        app_bin_path = makepath(app_dir, "bin", "code")
    elif get_os_name() == "Linux":
        app_dir = makepath("/", "usr", "share", "code")
        app_bin_path = makepath(app_dir, "bin", "code")
    elif get_os_name() == "Darwin":
        app_dir = makepath("/", "Applications", "Visual Studio Code.app")
        app_bin_path = makepath(app_dir, "Contents", "Resources", "app", "bin", "code")
    ext_path = glob.glob(makepath(app_dir, "*%s*.vsix" % ext_uid_name))[0]

    # Installing extension in user env
    print("Installing: %s extension in user env" % (ext_path))
    vsix_cmd = f'"{app_bin_path}" --install-extension "{ext_path}"'
    #if force or "2021.12.1559732655" in ext_path:
    #    vsix_cmd += " --force"
    result = run_notfatal(vsix_cmd)  # code extension always return exit status 0 for now
    print(result)
    # if "Failed Installing Extensions" in result and not force:
    #if "Failed Installing Extensions" in result or "A newer version of extension" in result and not force:
    #    print("Unable to install extension with: %s" % ext_path)
    #    print("Force install: %s extension in user env" % (ext_uid_name))
    #    # result_force = run_notfatal('"%s" --install-extension "%s" --force' % (app_bin_path, ext_uid_name))
    #    result_force = run_notfatal('"%s" --install-extension "%s" --force' % (app_bin_path, ext_uid_name + "@2021.12.1559732655"))
    #    print(result_force)
    #    if "Failed Installing Extensions" in result_force:
    #        print("Unable to force install %s extension" % ext_uid_name)

    # # Please disable Jupyter extension manually instead of this code since it can not be done silently
    # if not WAPT.is_installed("tis-vscode-jupyter"):
    #     # Disable Jupyter just once since it run VSCode...
    #     if not registry_readstring(HKEY_CURRENT_USER, r"SOFTWARE\WAPT\Code", "DisableJupyterOnce") == "Done":
    #         run_notfatal('"%s" --disable-extension "ms-toolsai.jupyter"' % (app_bin_path))
    #         registry_setstring(HKEY_CURRENT_USER, r"SOFTWARE\WAPT\Code", "DisableJupyterOnce", "Done")

def uninstall():
    # Initializing variables
    package_version = control.get_software_version()
    if get_os_name() == "Windows":
        app_dir = makepath(programfiles, "Microsoft VS Code")
        app_bin_path = makepath(app_dir, "bin", "code")
    elif get_os_name() == "Linux":
        app_dir = makepath("/", "usr", "share", "code")
        app_bin_path = makepath(app_dir, "bin", "code")
    elif get_os_name() == "Darwin":
        app_dir = makepath("/", "Applications", "Visual Studio Code.app")
        app_bin_path = makepath(app_dir, "Contents", "Resources", "app", "bin", "code")

    # Removing extensions from app_dir
    for ext in glob.glob(makepath(app_dir, "*%s*.vsix" % ext_uid_name)):
        print("Removing: %s" % ext)
        remove_file(ext)

    # Removing extension from user profiles
    killalltasks(["Code", "code"])
    print(remove_tree_for_all_users(makepath(".vscode", "extensions", "%s-*" % ext_uid_name)))


def remove_tree_for_all_users(user_folder_relative_path, ignored_users=None, ignore_system_users=True):
    r"""Remove a specific folder or folders for all user's profiles

    Args:
        user_folder_relative_path (str): relative path to user folder, glob patterns can be used
        ignored_users (str or list of str): ignore specified users
        ignore_system_users (bool): ignore default, public, all users, etc. True by default

    Returns:
        list: list of deleted folders

    >>> print(remove_tree_for_all_users(makepath(".vscode", "extensions", "ms-toolsai.jupyter-*")))
    ['C:\\Users\\username\\.vscode\\extensions\\ms-toolsai.jupyter-2022.2.1001817079', 'C:\\Users\\username\\.vscode\\extensions\\ms-toolsai.jupyter-keymap-1.0.0', 'C:\\Users\\username\\.vscode\\extensions\\ms-toolsai.jupyter-renderers-1.0.6']

    >>> print(remove_tree_for_all_users(makepath(".vscode", "extensions", "ms-toolsai.jupyter-")))
    []

    >>> print(remove_tree_for_all_users(makepath(".vscode", "extensions", "ms-toolsai.jupyter-[a-z]*")))
    ['C:\\Users\\username\\.vscode\\extensions\\ms-toolsai.jupyter-keymap-1.0.0', 'C:\\Users\\username\\.vscode\\extensions\\ms-toolsai.jupyter-renderers-1.0.6']

    >>> print(remove_tree_for_all_users(makepath(".vscode", "extensions", "ms-toolsai.jupyter-1.0.0")))
    ['/home/username/.vscode/extensions/ms-toolsai.jupyter-keymap-1.0.0']

    .. versionadded:: 2.3

    """
    system_users_list = ["All Users", "Default", "Default User", "Public", "Shared"]
    if ignored_users is None:
        ignored_users = []
    if type(ignored_users) != list:
        ignored_users = [ignored_users]

    deleted_folders = []
    skipped_users = []
    if ignored_users:
        skipped_users.extend(ignored_users)
    if ignore_system_users:
        skipped_users.extend(system_users_list)

    if get_os_name() == "Windows":
        users_dir = makepath(systemdrive, "Users")
    elif get_os_name() == "Linux":
        users_dir = "/home"
    elif get_os_name() == "Darwin":
        users_dir = "/Users"

    for user_profile in glob.glob("%s/*/" % users_dir):
        for ignored_user in ignored_users:
            if user_profile.rstrip(os.path.sep).split(os.path.sep)[-1] == ignored_user:
                continue
        for user_folder_to_delete in glob.glob(r"%s" % makepath(user_profile, user_folder_relative_path)):
            deleted_folders.append(user_folder_to_delete)
            remove_tree(user_folder_to_delete)
    return deleted_folders
