"""
Utility functions for hoppr plug-ins
"""
import urllib
from shutil import which

from hoppr.result import Result


def dir_name_from_repo_url(repo: str) -> str:
    """
    Creates a directory name based on a repo url
    """

    if repo.endswith("/") and not repo.endswith("://"):
        repo = repo[:-1]

    return urllib.parse.quote_plus(repo)


def repo_url_from_dir_name(dir_name: str) -> str:
    """
    Reconstitutes a repo url from a directory name generated by dir_name_from_repo_url
    """

    return urllib.parse.unquote_plus(dir_name)


def get_missing_commands(cmd_list):
    """
    Determine which items from a list of required commands are unavailable
    """

    missing_cmds = []

    if isinstance(cmd_list, list):
        for cmd in cmd_list:
            missing_cmds.extend(get_missing_commands(cmd))
    elif not which(cmd_list):
        missing_cmds.append(cmd_list)

    return missing_cmds


def check_for_missing_commands(cmd_list):
    """
    Raise an exception if any of a list of required commands are unavailable
    """
    missing_cmds = get_missing_commands(cmd_list)

    if len(missing_cmds) == 0:
        return Result.success()

    return Result.fail(
        f"The following required commands are unavailable: {', '.join(missing_cmds)}.  "
        + "Have them installed and try again."
    )
