import glob
import os
import subprocess

import appdirs
import click

from . import cloud
from . import node


# Bash script content to enable tab completion.
# This was generated by running `_PDTOOLS_COMPLETE=source pdtools`.
PDTOOLS_COMPLETE = """
_pdtools_completion() {
    COMPREPLY=( $( env COMP_WORDS="${COMP_WORDS[*]}" \
                   COMP_CWORD=$COMP_CWORD \
                   _PDTOOLS_COMPLETE=complete $1 ) )
    return 0
}

complete -F _pdtools_completion -o default pdtools;
"""


@click.command('wizard')
@click.pass_context
def root(ctx):
    """
    Set up environment for development.
    """
    click.echo("This wizard will help set up your development environment "
               "for programming with Paradrop.\n")

    config_dir = appdirs.user_config_dir('pdtools', 'paradrop')
    env_path = os.path.join(config_dir, 'env.sh')

    new_account = False
    have_account = click.confirm("Do you have a developer account on paradrop.org")
    if not have_account:
        if click.confirm("Would you like to register one now"):
            click.echo("")

            # Keep trying until the registration succeeds.
            result = None
            while result is None:
                result = ctx.invoke(cloud.register)
                click.echo("")

            # Set flags - user has an account, and it is new.
            have_account = True
            new_account = True

    if have_account:
        click.echo("Let's log in to your developer account. This will give you "
                   "the ability to manage compute nodes remotely and publish "
                   "chutes to the store.\n")

        # Warning for new accounts - we need them to verify their email.
        if new_account:
            click.echo("Important: Since this is a new developer account, "
                       "please make sure "
                       "you have followed the instructions in the email to "
                       "activate your account before proceeding to log in.\n")

        # Keep trying until login succeeds.
        result = False
        while not result:
            result = ctx.invoke(cloud.login)
            click.echo("")

        click.echo("Checking for nodes that are listed on your account...\n")
        ctx.invoke(cloud.list_nodes)
        click.echo("")

        while click.confirm("Do you have a claim token for a node not listed above"):
            token = click.prompt("Claim token").strip()
            ctx.invoke(cloud.claim_node, token=token)
            click.echo("")

    click.echo("If you have network access to a node, you can use the "
               "pdtools node commands for development and testing on "
               "the node.")
    have_node = click.confirm("Do you have a node to configure")
    ready = False
    while have_node and not ready:
        target = click.prompt("Node address").strip()
        click.echo("")

        click.echo("Let's log in to the node. This will give you direct "
                   "access to install and configure chutes on the node. "
                   "Please note that the node username/password is different "
                   "from your paradrop.org account.\n")

        ctx.obj['target'] = target
        ready = ctx.invoke(node.login)
        click.echo("")

    if have_node:
        click.echo("Next, we'll look for SSH public keys in order to enable "
                   "SSH access to your node.\n")

        search_path = os.path.expanduser("~/.ssh/*.pub")
        pubkeys = glob.glob(search_path)
        if len(pubkeys) == 0:
            click.echo("No keys were found in ~/.ssh/. We can generate one now "
                       "or you can do this later by running ssh-keygen "
                       "and adding the key with pdtools node import-ssh-key <path>.")
            if click.confirm("Generate an SSH key now"):
                cmd = ["ssh-keygen", "-b", "4096"]
                subprocess.call(cmd)

        for path in glob.iglob(search_path):
            if click.confirm("Use the public key {}".format(path)):
                ctx.invoke(node.import_ssh_key, path=path)

    with open(env_path, "w") as output:
        output.write("# This file was automatically generated by pdtools wizard.\n\n")
        output.write(PDTOOLS_COMPLETE)

    click.echo("")
    click.echo("Setup complete!\n")

    click.echo("If you would like to enable tab completion for pdtools "
               "run the following command next.\n")
    click.echo("  source {}\n".format(env_path))

    if have_node:
        click.echo("To run pdtools node commands on your target node without typing "
                   "the address every time, you can set the following variable.\n")
        click.echo("  export PDTOOLS_NODE_TARGET={}\n".format(target))

    click.echo("These changes will only apply to your current terminal session. "
               "To make the changes persistent, add these commands to your .bashrc "
               "or equivalent configuration file.")
