import json
import click
import traceback

from wurker.settings import conf
from wurker.plugin import load_plugins
from wurker.cli.base import CommandNotReady

from .command import AddCommand


def register_add_command(wurk):
    @wurk.command()
    @click.argument("option", type=click.Choice(['bee', 'cron', 'command', 'ondemand',]))
    @click.argument('infile', type=click.File('r'), default="-", required=False)
    @click.option("-d", "--drone", "drones", multiple=True, help="Slug or ID of drone(s) to add to (repeatable)")
    @click.pass_context
    def add(ctx, option, infile, drones):
        """Add Wurker definitions"""

        if not infile:
            raise click.ClickException("The 'add' command requires JSON input")

        # If the input is from a TTY, then no file was provided, so prompt the user.
        if infile.isatty():
            click.echo("Please enter JSON data. When done, press Ctrl-D to finish:")

        data = json.load(infile)

        try:
            logger = ctx.obj.get("logger")

            load_plugins(logger=logger)

            cmd = AddCommand(logger=logger)
            cmd.run(option, data, drones=drones)
        except CommandNotReady as ex:
            if conf.debug:
                click.echo(traceback.format_exc(), err=True)
            raise click.ClickException(f"The 'wurk add' command is not ready. Run 'wurk admin --help'. {ex}")
        except Exception as ex:
            if conf.debug:
                click.echo(traceback.format_exc(), err=True)
            raise click.ClickException(str(ex))
