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 import typealias as tp
from mower.utils.graph import SceneGraphSolver
from mower.utils.log import logger
from mower.utils.recognize import Scene


class GetOrderRemainingTimeSolver(SceneGraphSolver, BaseMixin):
    solver_name = "订单剩余时间"

    def run(self, room: str) -> int:
        """
        Returns:
            剩余时间（单位为秒）
        """
        self.room = room
        self.res = None
        self.wait_start()
        super().run()
        return self.res

    def number(self, scope: tp.Scope, height: int, thres: int) -> str:
        "数字识别"
        rect_limits = [{"w": 10, "h": 10, "char": ":"}]
        return config.recog.num.number(
            "riic_base", scope, height, thres, rect_limits=rect_limits
        )

    def read_remain_time(self, pos) -> int:
        h, m, s = self.number(pos, 19, 115).split("::")
        return int(h) * 3600 + int(m) * 60 + int(s)

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

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

    def transition(self) -> bool:
        if (
            scene := self.scene()
        ) == Scene.INFRA_DETAILS and self.detect_room() == self.room:
            self.ctap((200, 1000), 1, config.screenshot_avg / 1000)
            self.wait_start()
        elif scene == Scene.ORDER_LIST and self.detect_room_inside() == self.room:
            if self.timeout():
                logger.error("读取订单失败")
                return True
            elif pos := self.find("bill_accelerate"):
                pos[0][0] += 69
                pos[0][1] -= 214
                pos[1][0] -= 52
                pos[1][1] -= 220
                if res := self.read_remain_time(pos):
                    self.res = res
                    return True

        elif scene in self.waiting_scene:
            self.waiting_solver()
        else:
            EnterRoomSolver().run(self.room, detail=False)
