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, diff_ratio
from mower.utils.log import logger
from mower.utils.scene import Scene


# 按需填充干员
class BattleFillChooseSolver(SceneGraphSolver):
    solver_name = "标签填充干员"

    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
        self.before = None
        self.recog_agents = None
        super().run()
        logger.info(f"填充完成：{self.choosed}")
        return self.choosed

    @property
    def interval(self):
        return config.screenshot_avg / 500  # 截图延迟

    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] + 60, scope[0][1] - 113],
                    [scope[0][0] + 61, scope[0][1] - 112],
                ],
            )[0][0][0]
            < 50
        ) and cropimg(
            config.recog.img,
            [
                [scope[0][0] + 60, scope[1][1] + 216],
                [scope[0][0] + 61, scope[1][1] + 217],
            ],
        )[0][0][0] < 50:
            return True
        return False

    def fill_agent(self):
        if self.before is not None:
            self.sleep(0.1)
            if diff_ratio(self.before, config.recog.gray):
                logger.debug("滑动还在继续")
                self.before = config.recog.gray
                self.recog_agents = None
                return
            self.before = None

        if self.recog_agents is None:
            self.recog_agents = dict(operator_team_select(config.recog.img))

        if self.agent is None:
            for i in self.recog_agents:
                if self.is_choosed(self.recog_agents[i]) or i in self.black_list:
                    continue
                self.agent = i
                logger.info(f"开始选择：{self.agent}")
                break
            if self.agent is None:
                # 右滑
                self.recog_agents = dict(
                    self.swipe_update(
                        [(1600, 770), (600, 770), (600, 900)],
                        [300, 500],
                        up_wait=200,
                        interval=0.2,
                        func=operator_team_select,
                    )
                )
                tmp_img = config.recog.gray
                config.recog.update()
                if diff_ratio(tmp_img, config.recog.gray):
                    logger.info("填充干员不足")
                    return True

                self.before = config.recog.gray
                return

        if self.is_choosed(self.recog_agents[self.agent]):
            logger.info(f"选好{self.agent}")
            self.choosed.append(self.agent)
            self.agent = None
            if len(self.choosed) >= self.number:
                return True
        else:
            if self.recog_agents[self.agent][0][0] > 1650:
                logger.debug(f"右滑调整位置：{self.agent}")
                self.swipe_update(
                    [(700, 770), (400, 770), (400, 500)],
                    [200, 200],
                    up_wait=200,
                    interval=0.2,
                )
                return
            else:
                self.ctap(
                    self.recog_agents[self.agent], 2, self.interval, id=self.agent
                )
                return

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

            return self.fill_agent()
        elif scene in self.waiting_scene:
            self.waiting_solver()
        else:
            return True
