from datetime import datetime, timedelta

import cv2

from mower.utils import config
from mower.utils.email import send_message
from mower.utils.generate_image import generate_image
from mower.utils.graph import SceneGraphSolver
from mower.utils.log import logger
from mower.utils.recognize import Scene
from mower.utils.vector import sa, va, vs


class RogueNaviSolver(SceneGraphSolver):
    solver_name = "肉鸽导航"
    _title = {
        "Phantom": "古堡笔记",
        "Mizuki": "生态谱系",
        "Sami": "科考记录",
        "Sarkaz": "假说辑录",
    }
    _location = {
        "Phantom": (0, 0),
        "Mizuki": (551, 0),
        "Sami": (1100, 0),
        "Sarkaz": (1649, 0),
    }
    _max_level = {"Phantom": 155, "Mizuki": 170, "Sami": 155, "Sarkaz": 125}

    def generate_names(self):
        names = {}
        for name in self._location.keys():
            names[name] = generate_image(self._title[name], 25)
        self.names = names

    def run(self) -> bool:
        self.start_time = datetime.now()
        self.success = False
        self.full = False
        self.generate_names()
        super().run()
        config.conf.maa_rg_enable = 0 if self.full else 1
        config.save_conf()
        return self.success

    def transition(self):
        if datetime.now() - self.start_time > timedelta(minutes=2):
            logger.error("肉鸽导航超时")
            return True
        elif (scene := self.scene()) == Scene.TERMINAL_LONGTERM:
            self.tap((770, 750), interval=2)
        elif scene == Scene.ROGUE_THEME_SELECT:
            name, val, loc = None, 1, None
            for n, img in self.names.items():
                result = cv2.matchTemplate(config.recog.gray, img, cv2.TM_SQDIFF_NORMED)
                min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
                if min_val < val:
                    val = min_val
                    loc = min_loc
                    name = n
            logger.debug(f"在{loc}找到关卡{name}")
            target = va(
                vs(loc, self._location[name]), self._location[config.conf.maa_rg_theme]
            )
            if target[0] + 200 > 1920:
                self.swipe_noinertia((1400, 800), (-1000, 0))
            elif target[0] < 0:
                self.swipe_noinertia((400, 800), (1000, 0))
            else:
                if config.conf.rogue.mode == 0:  # 判断等级是否刷满
                    scope = sa(((-95, 2), (-5, 42)), target)
                    if scope[0][0] < 0:
                        self.swipe_noinertia((400, 800), (100, 0))
                        return
                    if (
                        config.recog.num.number_int("secret_front", scope, 33)
                        == self._max_level[config.conf.maa_rg_theme]
                    ):
                        send_message(
                            f"肉鸽：{config.conf.maa_rg_theme}等级已刷满",
                            level="WARNING",
                        )
                        self.full = True
                        return True
                for _ in range(2):  # 点两下进
                    self.tap(va(target, (60, 20)), interval=0.2)
        elif scene == Scene.ROGUE_INDEX:
            delta = (datetime.now() - self.start_time).total_seconds()
            logger.info(f"保全导航成功，用时{delta:.0f}秒")
            if config.conf.rogue.mode == 1:
                self.sleep(1.5)
                if self.find(f"rogue/full_money/{config.conf.maa_rg_theme}"):
                    self.full = True
                    send_message(
                        f"肉鸽:{config.conf.maa_rg_theme}源石锭已刷满", level="WARNING"
                    )
            self.success = True
            return True
        else:
            self.scene_graph_step(Scene.TERMINAL_LONGTERM)
