import cv2
from scipy.signal import argrelmin

from mower.solvers.navigation import NavigationSolver
from mower.utils import config
from mower.utils.email import send_message
from mower.utils.graph import SceneGraphSolver
from mower.utils.image import cropimg, loadres
from mower.utils.log import logger
from mower.utils.recognize import Scene

from .auto_fight import AutoFight
from .battle_choose import BattleChooseSolver


class CreditFight(SceneGraphSolver):
    """信用作战

    从首页导航至OF-1，借助战并自动战斗
    """

    def run(self, auto_choose: bool = False):
        logger.info("Start: 信用作战")
        self.support = False
        conf = config.conf.credit_fight
        self.opers = [{"name": conf.operator, "skill": 1, "skill_usage": 1}]
        self.actions = [
            {"type": "SpeedUp"},
            {
                "type": "Deploy",
                "name": conf.operator,
                "location": [
                    conf.x,
                    conf.y,
                ],
                "direction": conf.direction,
            },
            {"type": "SkillDaemon"},
        ]
        self.auto_choose = auto_choose
        super().run()

    def choose_support(self):
        img = cropimg(config.recog.gray, ((0, 908), (1839, 983)))
        res = loadres("fight/choose", True)
        result = cv2.matchTemplate(img, res, cv2.TM_SQDIFF_NORMED)[0]
        threshold = 0.1
        match = []
        for i in argrelmin(result, order=100)[0]:
            if result[i] < threshold:
                match.append(i)
        logger.debug(match)
        x = match[0]
        return (x, 908), (x + 194, 983)

    def transition(self):
        if (scene := self.scene()) == Scene.OPERATOR_SELECT:
            if self.auto_choose:
                BattleChooseSolver().run("OF-1", self.opers)
                self.auto_choose = False
            if self.find("ope_select_start_empty"):
                logger.info("编队内没有编入干员,停止OF-1")
                return True
            if self.support:
                # 开始行动
                AutoFight().run("OF-1", self.opers, self.actions)
            else:
                # 借助战
                self.ctap((1660, 315))
        elif scene == Scene.OPERATOR_SUPPORT:
            self.tap(self.choose_support())
            self.support = True
        elif scene == Scene.OPERATOR_SUPPORT_AGENT:
            self.tap_element("fight/use")
        elif scene == Scene.OPERATOR_FINISH:
            return True
        elif scene == Scene.OPERATOR_FAILED:
            msg = "OF-1失败，请检查干员，*今天*不会继续进行信用作战"
            logger.info(msg)
            send_message(msg, level="ERROR")
            return True
        elif scene in self.waiting_scene:
            self.waiting_solver()
        else:
            NavigationSolver().run("OF-1", "copy")
