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.email import send_message
from mower.utils.graph import SceneGraphSolver
from mower.utils.log import logger
from mower.utils.recognize import Scene


class ReloadSolver(SceneGraphSolver, BaseMixin):
    solver_name = "搓玉补货"

    def run(self, room) -> None:
        logger.info(f"开始补货:{room}")
        self.room = room
        self.success = False
        self.wait_start()
        super().run()

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

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

    def number(self, scope: tp.Scope, height: int, thres: int) -> int:
        "数字识别"
        return config.recog.num.number_int("riic_base", scope, height, thres)

    def transition(self) -> bool:
        if (
            scene := self.scene()
        ) == Scene.INFRA_DETAILS and self.detect_room() == self.room:
            self.wait_start()
            self.ctap((200, 1000), 1)
        elif scene == Scene.FACTORY_ROOMS and self.detect_room_inside() == self.room:
            reload_num = 99 - self.number(((1306, 462), (1391, 521)), 50, 200)
            if self.find("reload_check"):
                self.ctap((1400, 850), 1)
                self.success = True
            elif self.timeout():
                logger.warning(f"材料已耗尽:{self.room} 时间为:{datetime.now()}")
                send_message(f"材料已耗尽:{self.room}", level="WARNING")
                return True
            elif not self.success:
                if reload_num == 0:
                    logger.info(f"货已满:{self.room} 时间为:{datetime.now()}")
                    send_message(f"货已满:{self.room}")
                    return True
                else:
                    self.last_num = reload_num
                    self.tap((1450, 300))
            else:
                if reload_num == 0:
                    logger.info(
                        f"补货成功:{self.room} 本次补货数量:{self.last_num} 时间:{datetime.now()}"
                    )
                    send_message(f"补货成功:{self.room} 本次补货数量:{self.last_num}")
                    return True
                else:
                    logger.warning(
                        f"补货成功:{self.room} 剩余数量:{99-reload_num} 剩余材料不足! 时间:{datetime.now()}"
                    )
                    send_message(
                        f"补货成功:{self.room} 剩余数量:{99-reload_num} 剩余材料不足!",
                        level="WARNING",
                    )
                    return True
        elif scene in self.waiting_scene:
            self.waiting_solver()
        else:
            EnterRoomSolver().run(self.room, detail=False)
