import time

import vagary.schemas as schemas
from vagary.schemas import Scenario
from vagary.machine_manager import MachineManager

class Runner:
    def __init__(self, scenario: Scenario):
        self.scenario = scenario
        self.mm = MachineManager(scenario.machine)

    def run(self):
        self._run_setup()
        self._run_steps()
        self._run_teardown()

    def _run_setup(self):
        print("\n=== SETUP ===")
        self.mm.start()
        self.mm.connect_ssh()
        self.mm.connect_vnc()

    def _run_step(self, step: schemas.Step, indent: int = 0):
        print(step.format_step(indent))

        if isinstance(step, schemas.ScreenshotStep):
            self.mm.vnc_screenshot(step.path)
        if isinstance(step, schemas.ExpectRegionStep):
            self.mm.vnc_expect_region(step.path, step.pos.x, step.pos.y, maxrms=step.maxrms)
        if isinstance(step, schemas.KeyStep):
            self.mm.vnc_key(step.key)
        if isinstance(step, schemas.TypeStep):
            self.mm.vnc_type(step.text)
        if isinstance(step, schemas.ShellStep):
            self.mm.exec(step.run)
        if isinstance(step, schemas.ClickStep):
            self.mm.vnc_click(step.pos.x, step.pos.y)
        if isinstance(step, schemas.MoveStep):
            self.mm.vnc_move(step.pos.x, step.pos.y)
        if isinstance(step, schemas.GroupStep):
            for s in step.steps:
                self._run_step(s, indent=1)
        if isinstance(step, schemas.SleepStep):
            time.sleep(step.time)
        time.sleep(self.scenario.settings.sleep_between_steps)

    def _run_steps(self):
        print("\n=== STEPS ===")

        for step in self.scenario.steps:
            self._run_step(step)

    def _run_teardown(self):

        print("\n=== TEARDOWN ===")
        self.mm.close()
