from datetime import datetime, timedelta

from mower.solvers.infra.base_mixin import BaseMixin
from mower.solvers.infra.enter_room import EnterRoomSolver
from mower.utils import config
from mower.utils.graph import SceneGraphSolver
from mower.utils.recognize import Scene

from .utils import product


class CheckCurrentProductSolver(SceneGraphSolver, BaseMixin):
    def run(self, room) -> None:
        self.room = room
        if (
            self.scene() == Scene.FACTORY_ROOMS
            and not self.detect_room_inside() == self.room
        ):
            EnterRoomSolver().run(self.room, detail=False)
        self.wait_start()
        super().run()
        return self.res

    def timeout(self) -> bool:
        return datetime.now() > self.start_time + timedelta(seconds=5)

    def wait_start(self):
        self.start_time = datetime.now()

    def check_product(self) -> str:
        for p in product:
            if self.find(f"product/{p}"):
                return p

    def transition(self) -> bool:
        if (scene := self.scene()) == Scene.INFRA_DETAILS:
            self.wait_start()
            self.ctap((200, 1000), 1, config.screenshot_avg / 1000)
        elif scene == Scene.FACTORY_ROOMS:
            if res := self.check_product():
                self.res = res
                return True
            elif self.timeout():
                self.res = None
                return True
        elif scene in self.waiting_scene:
            self.waiting_solver()
        else:
            EnterRoomSolver().run(self.room, detail=False)
