from datetime import timedelta

from mower.utils import config
from mower.utils.graph import SceneGraphSolver
from mower.utils.image import cropimg, diff_ratio
from mower.utils.recognize import Scene


class MissionSolver(SceneGraphSolver):
    solver_name = "每日/每周任务"
    solver_max_duration = timedelta(minutes=2)

    def run(self) -> None:
        self.daily = False
        return super().run()

    def animation(self):
        scope = (0, 0), (560, 1080)
        img1 = cropimg(config.recog.gray, scope)
        self.sleep()
        img2 = cropimg(config.recog.gray, scope)
        return diff_ratio(img1, img2, thresh=20)

    def transition(self):
        if (scene := self.scene()) == Scene.MISSION_DAILY:
            if self.daily:
                self.tap("mission_weekly")
                return
            if pos := self.find("mission_collect"):
                self.tap(pos)
                return
            if self.animation():
                self.solver_update_before_transition = False
                return
            self.daily = True
            self.solver_update_before_transition = False
        elif scene == Scene.MISSION_WEEKLY:
            if not self.daily:
                self.tap("mission_daily")
                return
            if pos := self.find("mission_collect"):
                self.tap(pos)
                return
            if self.animation():
                self.solver_update_before_transition = False
                return
            return True
        else:
            self.scene_graph_step(Scene.MISSION_DAILY)
