class TriggerScriptRunHandler(EventHandler):
    """
    Handles TriggerScriptRunHandler Events
    """
    def __init__(self, loop, event_bus, logger, config=None):
        super().__init__(loop, event_bus, logger, config)
        self.script_execution_manager = ScriptExecutionManager(loop)

        self.event_bus.subscribe(events.TriggerScriptRunEvent,
                                 self.handle_trigger_script_run_event)

        self.started = True

    async def handle_trigger_script_run_event(self, event):
        script = await ScriptEntity.filter(name=event.data["name"]).first()

        if script is not None:
            self.script_execution_manager.schedule_script(
                script.name, script.script_contents, None)
        else:
            msg = f"Attempted to trigger script run for script \"{event.data['name']}\" but this script does not exist in the database."
            self.logger.warn(msg)

            run_script_event = events.RunScriptResultEvent().init({
                "name":
                event.data["name"],
                "error":
                msg,
                "log":
                ""
            })
            get_supervisor().fire_event(run_script_event)
    def __init__(self, loop, event_bus, logger, config=None):
        super().__init__(loop, event_bus, logger, config)
        self.script_execution_manager = ScriptExecutionManager(loop)

        self.event_bus.subscribe(events.TriggerScriptRunEvent,
                                 self.handle_trigger_script_run_event)

        self.started = True
class AddScriptHandler(EventHandler):
    """
    Handles AddScript Events
    """
    def __init__(self, loop, event_bus, logger, config=None):
        super().__init__(loop, event_bus, logger, config)
        self.event_bus.subscribe(events.AddScriptEvent,
                                 self.handle_add_script_event)
        self.script_manager = ScriptExecutionManager(loop)

    async def handle_add_script_event(self, event):
        coro = ScriptEntity.filter(name=event.data["name"])
        coro2 = coro.first()
        result = await coro2

        if not result:
            self.logger.debug(
                f"Script upload recieved for script \"{event.data['name']}\"")

            crontab = event.data.get("crontab", None)

            insert_new_script = ScriptEntity.create(
                name=event.data["name"],
                crontab=crontab,
                script_contents=event.data["script_contents"],
            )
            await insert_new_script

            # schedule script
            if crontab:
                self.logger.debug(
                    f"Scheduling script \"{event.data['name']}\"")
                self.script_manager.schedule_script(
                    event.data["name"], event.data["script_contents"], crontab)
            else:
                self.logger.debug(
                    "Not scheduling uploaded script \"{event.data['name']} as crontabe is None."
                )

        else:
            self.logger.error(
                f"Script upload received for script \"{event.data['name']}\", but a script with this name already exists."
            )

            new_event = events.AddScriptFailedEvent()
            new_event.init({
                "error":
                f"Failed to add script {event.data['name']}.",
                "description":
                "A script with this name already exists.",
                "description_verbose":
                ("A script with this name already exists. Delete the script with "
                 "this name then try again, or change the name of the script you are attempting to upload"
                 ),
            })
            get_supervisor().fire_event(new_event)
class StartupEventHandler(EventHandler):
    """
    Handles Startup Event to start the script manager
    """
    def __init__(self, loop, event_bus, logger, config=None):
        super().__init__(loop, event_bus, logger, config)
        self.script_manager = ScriptExecutionManager(loop)

        self.event_bus.subscribe(signal_events.StartupEvent,
                                 self.handle_startup_event)

    async def handle_startup_event(self, event):
        for script in await ScriptEntity.all():
            if script.crontab is not None:
                self.script_manager.schedule_script(script.name,
                                                    script.script_contents,
                                                    script.crontab)

        self.event_bus.unsubscribe(signal_events.StartupEvent,
                                   self.handle_startup_event)
    def __init__(self, loop, event_bus, logger, config=None):
        super().__init__(loop, event_bus, logger, config)
        self.script_execution_manager = ScriptExecutionManager(loop)

        self.event_bus.subscribe(events.TriggerDeleteScriptEvent,
                                 self.handle_trigger_delete_script_event)
 def __init__(self, loop, event_bus, logger, config=None):
     super().__init__(loop, event_bus, logger, config)
     self.event_bus.subscribe(events.AddScriptEvent,
                              self.handle_add_script_event)
     self.script_manager = ScriptExecutionManager(loop)
    def __init__(self, loop, event_bus, logger, config=None):
        super().__init__(loop, event_bus, logger, config)
        self.script_manager = ScriptExecutionManager(loop)

        self.event_bus.subscribe(signal_events.StartupEvent,
                                 self.handle_startup_event)