from datetime import datetime

from mower.solvers.infra.filter import RIIC_Filter
from mower.solvers.infra.riic_tag_choose import RIICTagChoose
from mower.utils import config
from mower.utils.character_recognize import operator_room_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 RIIC_FreeFillSolver(SceneGraphSolver):
    def run(self) -> bool:
        self.agent = None
        self.filterd = False
        self.tap_time = datetime.now()  # 临时解决
        super().run()

        return self.agent

    def fill_agent(self):
        if (self.tap_time - datetime.now()).total_seconds() > 180:
            raise TimeoutError(f"选择Free干员{self.agent}超时")

        if pos := self.find("choose_agent/riic/open_profession"):
            self.ctap(pos, interval=config.screenshot_avg / 1000, max_seconds=1)
            return

        agents = dict(operator_room_select(config.recog.img))

        if self.agent is None:
            for i in agents:
                # if i in 黑名单:
                #     continue
                pt_0 = agents[i][0][0]
                pt_1 = agents[i][0][1]
                color = cropimg(
                    config.recog.gray,
                    [
                        [pt_0 + 55, pt_1 - 80],
                        [pt_0 + 56, pt_1 - 79],
                    ],
                )[0][0]
                logger.info(
                    f"{i} {agents[i]} {color}{color < 200} {pt_0} {pt_1} {self.is_choosed(agents[i])}"
                )
                if color < 200 or self.is_choosed(agents[i]):
                    continue
                self.agent = i
                return

            # 无满足条件
            if (
                list(agents.keys())[-1] == self.tmp_data
                or list(agents.keys())[-1] is None
            ):
                raise ValueError(f"选择干员: {self.agent}失败 滑动次数过多")

            self.swipe_noinertia((1000, 540), (-1900, 0))
            self.tmp_data = list(agents.keys())[-1]
        else:
            if self.is_choosed(agents[self.agent]):
                return True

            # 左滑一点防止点击失效
            if agents[self.agent][0][0] > 1720:
                self.swipe_noinertia((1000, 540), (-500, 0))
                return
            logger.info(f"干员选择：{self.agent}")
            self.ctap(agents[self.agent], 2, config.screenshot_avg / 1000)
            return

    def is_choosed(self, scope) -> bool:
        if (
            cropimg(
                config.recog.img,
                [
                    [scope[0][0] + 0, scope[0][1] - 128],
                    [scope[0][0] + 1, scope[0][1] - 127],
                ],
            )[0][0][0]
            < 50
        ) and cropimg(
            config.recog.img,
            [
                [scope[0][0] + 0, scope[1][1] + 212],
                [scope[0][0] + 1, scope[1][1] + 213],
            ],
        )[0][0][0] < 50:
            return True
        return False

    def transition(self) -> bool:
        if (scene := self.scene()) == Scene.RIIC_OPERATOR_SELECT:
            if self.filterd is False:
                if RIIC_Filter().run("心情", ascending=True) and RIICTagChoose().run(
                    "ALL"
                ):
                    self.filterd = True

                return

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