import os
import click
import traceback

from wurker.settings import conf

from .command import StingerCommand


def register_stinger_command(admin):

    root = os.path.join(conf.etc_root, "stingers")

    ## The 'admin.stinger' subgroup
    @admin.group("stinger")
    @click.pass_context
    def stinger(ctx):
        """Manage injected Wurker resources"""
        pass


    @stinger.command()
    @click.option("--root", default=root, help=f"Path to root of stingers tree (default: '{root}')")
    @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.pass_context
    def sting(ctx, root, slug, node, env):
        """Inject resources from a Wurker Stinger repository"""

        try:
            logger = ctx.obj.get("logger")
            command = StingerCommand(logger=logger)
            command.run("sting", root=root, slug=slug, node=node, env=env)
        except Exception as ex:
            if conf.debug:
                click.echo(traceback.format_exc(), err=True)
            raise click.ClickException(str(ex))


    @stinger.command()
    @click.option("--drop-schema", is_flag=True, help="Also drop database schema")
    @click.pass_context
    def unsting(ctx, drop_schema):
        """Remove injected resources from Wurker"""

        try:
            logger = ctx.obj.get("logger")
            command = StingerCommand(logger=logger)
            command.run("unsting", drop_schema=drop_schema)
        except Exception as ex:
            if conf.debug:
                click.echo(traceback.format_exc(), err=True)
            raise click.ClickException(str(ex))


    @stinger.command()
    @click.option("--root", default=root, help=f"Path to root of stingers tree (default: '{root}')")
    @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("--drop-schema", is_flag=True, help="Also drop database schema")
    @click.pass_context
    def resting(ctx, root, slug, node, env, drop_schema):
        """Re-inject resources from a Wurker Stinger repository"""

        try:
            logger = ctx.obj.get("logger")
            command = StingerCommand(logger=logger)
            command.run("resting", root=root, slug=slug, node=node, env=env, drop_schema=drop_schema)
        except Exception as ex:
            if conf.debug:
                click.echo(traceback.format_exc(), err=True)
            raise click.ClickException(str(ex))


    ### The 'admin.stinger.extract' subsubgroup
    EXTRACT_CHOICES = [
        'requirements.txt', 'wurker.toml', 'seeds', 'models', 'bees',
        'settings', 'settings/bees', 'lib', 'lib/mail', 'ssl', 'data',
    ]

    @stinger.group("extract")
    @click.pass_context
    def extract(ctx):
        """Extract resources from Wurker to a Stinger repository"""
        pass


    @extract.command()
    @click.option(
        "-r", "--resource", "resources", multiple=True, default=[], type=click.Choice(EXTRACT_CHOICES),
        help="Which resources to extract (default: ALL)"
    )
    @click.option("--root", default=root, help=f"Path to root of stingers tree (default: '{root}')")
    @click.option("--slug", required=True, help="Stinger slug (ex: 'default')")
    @click.option("--node", required=True, help="Colony node slug (ex: 'queen')")
    @click.option("--env", required=True, help="Environment slug (ex: 'local')")
    @click.pass_context
    def wurker(ctx, resources, root, slug, node, env):
        """Extract resources to a 'wurker' directory"""

        try:
            logger = ctx.obj.get("logger")
            command = StingerCommand(logger=logger)
            command.run("extract", target="wurker", root=root, slug=slug, node=node, env=env, resources=resources)
        except Exception as ex:
            if conf.debug:
                click.echo(traceback.format_exc(), err=True)
            raise click.ClickException(str(ex))


    @extract.command()
    @click.option(
        "-r", "--resource", "resources", multiple=True, default=[], type=click.Choice(EXTRACT_CHOICES),
        help="Which resources to extract (default: ALL)"
    )
    @click.option("--root", default=root, help=f"Path to root of stingers tree (default: '{root}')")
    @click.option("--slug", required=True, help="Stinger slug (ex: 'default')")
    @click.option("--node", required=True, help="Colony node slug (ex: 'queen')")
    @click.option("--env", required=True, help="Environment slug (ex: 'local')")
    @click.pass_context
    def colony(ctx, resources, root, slug, node, env):
        """Extract resources to a 'colony' directory"""

        try:
            logger = ctx.obj.get("logger")
            command = StingerCommand(logger=logger)
            command.run("extract", target="colony", root=root, slug=slug, node=node, env=env, resources=resources)
        except Exception as ex:
            if conf.debug:
                click.echo(traceback.format_exc(), err=True)
            raise click.ClickException(str(ex))


    # The 'refactor' command
    @stinger.command()
    @click.option("--root", default=root, help=f"Path to root of stingers tree (default: '{root}')")
    @click.pass_context
    def refactor(ctx, root):
        """Refactor a legacy stinger tree"""

        try:
            logger = ctx.obj.get("logger")
            command = StingerCommand(logger=logger)
            command.run("refactor", root=root)
        except Exception as ex:
            if conf.debug:
                click.echo(traceback.format_exc(), err=True)
            raise click.ClickException(str(ex))
