from datetime import datetime, timedelta

import cv2

from mower.models import Digtal
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.image import cropimg, thres2
from mower.utils.log import logger
from mower.utils.recognize import Scene


class ReloadSolver(SceneGraphSolver, BaseMixin):
    def run(self, room) -> None:
        logger.info(f"开始补货:{room}")
        self.room = room
        self.success = False
        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()

    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:
        "数字识别"
        img = cropimg(config.recog.gray, scope)
        default_height = 25
        if height != default_height:
            scale = 25 / height
            img = cv2.resize(img, None, None, scale, scale)
        img = thres2(img, thres)
        contours, _ = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
        rect = [cv2.boundingRect(c) for c in contours]
        rect.sort(key=lambda c: c[0])

        value = 0

        for x, y, w, h in rect:
            digit = cropimg(img, ((x, y), (x + w, y + h)))
            digit = cv2.copyMakeBorder(
                digit, 10, 10, 10, 10, cv2.BORDER_CONSTANT, None, (0,)
            )
            score = []
            for i in range(10):
                im = Digtal().riic_base_digits[i]
                result = cv2.matchTemplate(digit, im, cv2.TM_SQDIFF_NORMED)
                min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
                score.append(min_val)
            value = value * 10 + score.index(min(score))

        return value

    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:
            reload_num = 99 - self.number(((1306, 462), (1391, 521)), 50, 200)
            if self.find("reload_check"):
                self.ctap((1400, 850), 1, config.screenshot_avg / 1000)
                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)
