import click

from wurker.settings import conf
from wurker.db import get_drone_status
from wurker.cli.base import BaseCommand
from wurker.core import Wurkman
from wurker.drone import make_drone_clients


class KillCommand(BaseCommand):
    """Encapsulate kill command."""

    def __init__(self, logger=None):
        BaseCommand.__init__(self, logger=logger, check_schema=True)

        # We might need drone API auth
        self.drone_api_auth = conf.ApiAuth


    def run(self, option:str='', key:str='', drones:list=[]):
        """Kill Wurker Bees, in various ways."""

        # Run via Drone API?
        if drones:
            return self.run_drone(option=option, key=key, drones=drones)

        wurkman = Wurkman(session=self.RemoteSession, logger=self.logger)

        if not option:
            return wurkman.kill()


        bees = {}
        if option in ["supervised", "scheduled", "ondemand"]:
            bees, _ = wurkman.get_bees(wurk_type=option)
        elif option == "hive":
            bees = wurkman.get_hive()
        else:
            bees, _ = wurkman.get_bees(slug_type=option, slug=key)

        # OK got some bees to kill (poor bees!)
        if bees:
            wurkman.kill(bees)


    def run_drone(self, option:str='', key:str='', drones:list=[]):
        """Run via Drone API(s)."""

        drone_status = get_drone_status(self.remote_db_conf, self.app_id, drones=drones)
        if drone_status is None or not len(drone_status):
            click.echo(f"WARNING: Queen ({self.app_id}) Drones have no 'wurker_status' data", err=True)
            return

        drone_clients = make_drone_clients(drone_status, auth=self.drone_api_auth)

        for app_id, drone in drone_clients.items():
            drone.post_kill(option, key)
