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.graph import SceneGraphSolver
from mower.utils.image import cropimg, thres2
from mower.utils.recognize import Scene


class ReadOriginalOrderRemainTimeSolver(SceneGraphSolver, BaseMixin):
    """
    返回剩余时间,换算为秒
    """

    def run(
        self,
        room: str,
    ):
        self.room = room
        if (
            self.scene() == Scene.DRONE_ACCELERATE
            and not self.detect_room_inside() == self.room
        ):
            EnterRoomSolver().run(self.room, detail=False)
        super().run()
        return self.res

    def number(self, scope: tp.Scope, height: int, thres: int) -> str:
        "数字识别"
        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 = ""
        for x, y, w, h in rect:
            if h < 7 and w < 7:
                value += ":"
                continue
            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 += str(score.index(min(score)))

        return value

    def read_remain_time(self) -> int:
        h, m, s = self.number(((758, 670), (960, 705)), 30, 100).split("::")
        return int(h) * 3600 + int(m) * 60 + int(s)

    def transition(self) -> bool:
        if (scene := self.scene()) == Scene.INFRA_DETAILS:
            self.ctap((200, 1000), 1, config.screenshot_avg / 1000)
        elif scene == Scene.ORDER_LIST:
            if pos := self.find("bill_accelerate"):
                self.tap(pos)

        elif scene == Scene.DRONE_ACCELERATE:
            if res := self.read_remain_time():
                self.res = res
                return True
        elif scene in self.waiting_scene:
            self.waiting_solver()
        else:
            EnterRoomSolver().run(self.room, detail=False)
