from datetime import datetime, timedelta

from mower.utils import config
from mower.utils.graph import SceneGraphSolver
from mower.utils.image import cmatch, cropimg, loadres
from mower.utils.log import logger
from mower.utils.recognize import Scene
from mower.utils.vector import va

from .utils import generate_image

xl = list(range(230, 1655, 473))
yl = [230, 573]
sl = []
for y in yl:
    for x in xl:
        tl = (x, y)
        sl.append((tl, va(tl, (10, 10))))


class SSSNaviSolver(SceneGraphSolver):
    def run(self, stage_name: str, buff: str, equipment: list) -> bool:
        logger.info("Start: 保全导航")
        self.start_time = datetime.now()
        self.success = False
        self.mode = config.conf.sss.mode  # "normal"：正常模式，"ex"：应急模式
        self.choose_agent = config.conf.sss.choose_agent
        self.type = generate_image(stage_name, 36)
        self.ec = generate_image(buff, 30)
        self.device: list[str] = equipment

        super().run()
        return self.success

    def get_device(self) -> list[str]:
        A = loadres("sss/A")
        result = []
        for scope in sl:
            img = cropimg(config.recog.img, scope)
            result.append("A" if cmatch(A, img, 60) else "B")
        logger.debug(result)
        return result

    def transition(self):
        if datetime.now() - self.start_time > timedelta(minutes=2):
            logger.error("保全导航超时")
            return True
        elif (scene := self.scene()) in [Scene.SSS_DEPLOY, Scene.SSS_REDEPLOY]:
            delta = (datetime.now() - self.start_time).total_seconds()
            logger.info(f"保全导航成功，用时{delta:.0f}秒")
            self.success = True
            return True
        elif scene == Scene.SSS_MAIN:
            score, scope = config.recog.matcher.match(self.type)
            if score > 0.85:
                pos = self.get_pos(scope)
                self.tap(va(pos, (-240, 0)))
        elif scene == Scene.SSS_START:
            if self.mode == "normal" and self.find("sss/switch_to_normal"):
                self.tap_element("sss/switch_to_normal")
                return
            elif self.mode == "ex" and self.find("sss/switch_to_ex"):
                self.tap_element("sss/switch_to_ex")
                return
            self.tap((1555, 966))
        elif scene == Scene.SSS_EC:
            score, scope = config.recog.matcher.match2d(self.ec)
            if score > 0.8:
                self.tap(scope)
                self.tap_element("sss/ec")
        elif scene == Scene.SSS_DEVICE:
            current = self.get_device()
            for i in range(8):
                if current[i] != self.device[i]:
                    self.tap(sl[i])
                    return
            self.tap_element("sss/device")
        elif scene == Scene.SSS_SQUAD:
            self.tap_element("sss/squad")
        elif scene == Scene.SSS_EC_EX:
            self.tap_element("sss/check_ex")

        else:
            self.scene_graph_step(Scene.SSS_MAIN)
