import cv2
import numpy as np

from mower.utils import config
from mower.utils.graph import SceneGraphSolver
from mower.utils.log import logger
from mower.utils.scene import Scene


class RIIC_Filter(SceneGraphSolver):
    def run(self, tag: str, ascending: bool = True) -> None:
        self.orders = ["工作状态", "技能", "心情", "信赖值"]
        if tag not in self.orders:
            raise KeyError

        self.tag = tag
        self.ascending = ascending
        self.tag_choose_done = False

        super().run()

        return True

    def detect_arrange_order(self):
        x_list = (1310, 1435, 1560, 1687)
        y = 70
        mask = cv2.inRange(config.recog.hsv, (95, 100, 100), (105, 255, 255))
        for idx, x in enumerate(x_list):
            if np.count_nonzero(mask[y : y + 3, x : x + 5]):
                return self.orders[idx], True
            if np.count_nonzero(mask[y + 10 : y + 13, x : x + 5]):
                return self.orders[idx], False

    def switch_arrange_order(self, name, ascending=False):
        name_x = {"工作状态": 1310, "技能": 1435, "心情": 1560, "信赖值": 1687}
        if isinstance(name, int):
            name = list(name_x.keys())[name - 1]
        if isinstance(ascending, str):
            ascending = ascending == "true"
        name_y = 60
        self.tap((name_x[name], name_y), interval=0.5)

    def transition(self) -> bool:
        if (scene := self.scene()) == Scene.RIIC_OPERATOR_SELECT:
            n, s = self.detect_arrange_order()
            if n != self.tag or s != self.ascending:
                logger.debug(f"{n}:{s}->{self.tag}:{self.ascending}")
                self.switch_arrange_order(self.tag, self.ascending)
                return
            return True
        elif scene in self.waiting_scene:
            self.waiting_solver()
        else:
            return True
