import click
import traceback

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

from .command import ControlCommand


def register_control_command(admin):
    @admin.command()
    @click.argument("action", type=click.Choice(['reload', 'pause']))
    @click.option("-d", "--drone", "drones", multiple=True, help="Slugs or ID of drone(s) to control (repeatable)")
    @click.pass_context
    def control(ctx, action, drones):
        """Reload or pause Wurker instance(s)"""

        try:
            cmd = ControlCommand()
            cmd.run(action, drones=drones)
        except CommandNotReady as ex:
            if conf.debug:
                click.echo(traceback.format_exc(), err=True)
            raise click.ClickException(
                f"The 'wurk admin control' 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))
