from mower.solvers.fight.battle_choose.battle_filter import BattleFilterSolver
from mower.solvers.fight.battle_choose.battle_tag_choose import BattleTagChoose
from mower.utils import config
from mower.utils.character_recognize import operator_team_select
from mower.utils.graph.utils import SceneGraphSolver
from mower.utils.image import cropimg
from mower.utils.log import logger
from mower.utils.scene import Scene


# 按需填充干员
class BattleFillChooseSolver(SceneGraphSolver):
    def run(self, label: str, number: int, black_list: list = []):
        if number <= 0:
            return []
        self.mode = None
        self.labels = [
            "获取时间",
            "信赖值",
            "生命上限",
            "攻击",
            "防御",
            "法术抗性",
            "再部署",
            "部署费用",
            "阻挡数",
            "攻击速度",
            "等级",
            "稀有度",
        ]

        self.profession = [
            "PIONEER",
            "WARRIOR",
            "TANK",
            "SNIPER",
            "CASTER",
            "MEDIC",
            "SUPPORT",
            "SPECIAL",
        ]

        # 0是非职业的筛选，如信赖值或等级
        if label in self.labels:
            self.mode = 0
        # 1是干员职业的筛选
        elif label in self.profession:
            self.mode = 1
        else:
            raise KeyError(f"BattleAgentChooseSolver：填充干员标签错误{label}")
        self.label = label
        self.filter_done = False
        self.resort = False
        self.number = number
        self.choosed = []
        self.black_list = black_list
        self.tmp_data = {}
        self.wait_choose = None
        self.agent = None
        super().run()
        logger.info(f"填充完成：{self.choosed}")
        return self.choosed

    def filter(self):
        if pos := self.find("choose_agent/open_profession"):
            self.tap(pos, interval=0.1)
            return

        if self.mode == 1:
            return BattleTagChoose().run(self.label) and BattleFilterSolver().run(
                "等级", False
            )
        elif self.mode == 0:
            if BattleFilterSolver().run(self.label):
                # 选全部干员
                if self.find("choose_agent/foldup"):
                    return True
                else:
                    return BattleTagChoose().run("ALL")
        return

    def is_choosed(self, scope) -> bool:
        if (
            cropimg(
                config.recog.img,
                [
                    [scope[0][0] + 0, scope[0][1] - 86],
                    [scope[0][0] + 1, scope[0][1] - 85],
                ],
            )[0][0][0]
            < 50
        ):
            return True
        return False

    def fill_agent(self):
        agents = dict(operator_team_select(config.recog.img))
        if self.agent is None:
            for i in agents:
                if self.is_choosed(agents[i]) or i in self.black_list:
                    continue
                self.agent = i
                break
            if self.agent is None:
                self.swipe_noinertia((1000, 540), (-1900, 0))
        else:
            agent_name = self.agent
            if agent_name in agents.keys():
                if agents[agent_name][0][0] > 1650:
                    self.swipe_noinertia((1000, 540), (-500, 0))
                    return
                if self.is_choosed(agents[agent_name]):
                    logger.debug(f"选择填充干员完成：{agent_name}")
                    self.choosed.append(agent_name)
                    if len(self.choosed) >= self.number:
                        return True
                    else:
                        self.agent = None
                        return
                logger.info(f"选择填充干员：{agent_name}")
                self.ctap(agents[agent_name], 1, config.screenshot_avg / 1000)
                return

    def transition(self) -> bool:
        if self.scene() == Scene.OPERATOR_AGENT_SELECT:
            if self.find("fight/collection_on"):
                self.tap_element("fight/collection_on")
                return
            if self.filter_done is False:
                if self.filter():
                    self.filter_done = True
                    return

            return self.fill_agent()
        else:
            return False
