import os
import click
import traceback

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

from .command import InitCommand


def register_init_command(admin):

    @admin.command()
    @click.option("--only", type=click.Choice(['wurker', 'local']),
                  help="Only initialize (or drop) the given database")
    @click.option("--drop", is_flag=True, help="Drop the given schema instead")
    @click.option("--no-status", is_flag=True, help="Skip printing status after init")
    @click.option("--root", default=os.path.join(conf.etc_root, "stingers"),
                  help="Path to root of stingers tree")
    @click.option("--slug", default="default", help="Stinger slug (default: 'default')")
    @click.option("--node", default="queen", help="Colony node slug (default: 'queen')")
    @click.option("--env", default="local", help="Environment slug (default: 'local')")
    @click.option("--username", default="", help="UI username to set in data/user.json")
    @click.option("--password", default="", help="UI password to set in data/user.json")
    @click.pass_context
    def init(ctx, only, drop, no_status, root, slug, node, env, username, password):
        """Initialize schema and seed data for a new install"""

        error = None
        try:
            logger = ctx.obj.get("logger")
            cmd = InitCommand(
                only=only,
                drop=drop,
                status=not no_status,
                root=root,
                slug=slug,
                node=node,
                env=env,
                username=username,
                password=password,
                logger=logger,
            )
            error = cmd.run()
        except CommandNotReady as ex:
            if conf.debug:
                click.echo(traceback.format_exc(), err=True)
            raise click.ClickException("The 'wurk admin init' command is not ready. "
                                       f"Run 'wurk admin stinger sting' first. {ex}")
        except Exception as ex:
            if conf.debug:
                click.echo(traceback.format_exc(), err=True)
            raise click.ClickException(str(ex))

        if error:
            click.echo(f"ERROR: {error}")
