from wurker.settings import conf
from wurker.cli.base import BaseCommand
from wurker.drone import make_drone_clients
from wurker.db import set_control, get_drone_status


class ControlCommand(BaseCommand):
    """Encapsulate the control operations."""

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

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


    def run(self, action:str, drones:list=[]):
        """Control the Wurker Bee Hive from the CLI."""

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

        if action == "reload":
            set_control(self.remote_db_conf, self.app_id, engine=self.remote_db_engine, key="reload", value=True)
        elif action == "pause":
            set_control(self.remote_db_conf, self.app_id, engine=self.remote_db_engine, key="pause", value=True)


    def run_drone(self, action: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):
            return

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

        for app_id, drone in drone_clients.items():
            drone.post_control(action)
