import cv2
from scipy.signal import argrelmax

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


class ChooseSkillSolver(SceneGraphSolver):
    "选择干员技能"

    def run(self, skill: int):
        logger.info(f"选择{skill}技能")
        self.skill = skill
        self.reverse = False
        super().run()

    def match_light(self):
        "找闪电确定技能位置"
        x = 88
        img = cropimg(config.recog.img, ((x, 600), (112, 1080)))
        threshold = 0.7
        res = loadres("fight/light")
        result = cv2.matchTemplate(img, res, cv2.TM_CCOEFF_NORMED).T[0]
        print(result)
        pos_list = []
        for i in argrelmax(result, order=50)[0]:
            if result[i] > threshold:
                pos_list.append((x, i + 600))
        logger.debug(pos_list)
        return pos_list

    def skill_be_choosen(self, y) -> bool:
        "技能是否被选择"
        img = cropimg(config.recog.img, ((539, y), (544, y + 5)))
        res = loadres("fight/skill_be_choosen")
        return cmatch(img, res, 70)

    def transition(self):
        if (scene := self.scene()) == Scene.OPERATOR_AGENT_SELECT:
            if self.skill > len(pos_list := self.match_light()) and not self.reverse:
                self.swipe_noinertia((300, 800), (0, -500), interval=0.5)
                self.reverse = True
                self.sleep(0.5)
            elif self.reverse:
                if self.skill_be_choosen(pos_list[-1][1]):
                    return True
                else:
                    self.tap(pos_list[-1])
            elif self.skill_be_choosen(pos_list[self.skill - 1][1]):
                return True
            else:
                self.tap(pos_list[self.skill - 1])
        elif scene in self.waiting_scene:
            self.waiting_solver()
        else:
            return
