from datetime import timedelta

import cv2

from mower.utils import config
from mower.utils.email import notify
from mower.utils.graph import SceneGraphSolver
from mower.utils.image import cropimg
from mower.utils.rapidocr import ocr_rec
from mower.utils.scene import Scene
from mower.utils.vector import sa

activity_name = "感谢庆典补给签到"


class SignIn(SceneGraphSolver):
    solver_name = "签到活动"
    solver_max_duration = timedelta(minutes=2)

    def run(self):
        self.in_progress = False
        return super().run()

    def transition(self) -> bool:
        if (scene := self.scene()) == Scene.MATERIEL:
            if self.in_progress:
                self.sleep()
                notify(f"{activity_name}奖励领取")
            self.tap((960, 960))
        elif scene == Scene.INDEX:
            score, scope = config.recog.match("sign_in/entry")
            if score < 0.8:
                notify(f"未找到{activity_name}入口")
                return True
            img = cropimg(config.recog.gray, scope)
            h, w = img.shape
            lh = h // 2
            line1 = cropimg(img, ((0, 0), (w, lh)))
            line2 = cropimg(img, ((0, lh), (w, h)))
            text = ocr_rec(line1) + ocr_rec(line2)
            if text != activity_name:
                notify(f"未找到{activity_name}入口")
                return True
            self.tap(scope)
        elif scene == Scene.SIGN_IN_DAILY:
            top_left = 680, 500
            img = cropimg(config.recog.hsv, (top_left, (1800, 540)))
            img = cv2.inRange(img, (165, 200, 100), (180, 255, 255))
            contours, _ = cv2.findContours(
                img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE
            )
            rect = [cv2.boundingRect(c) for c in contours]
            rect = [r for r in rect if r[2] > 200]
            if len(rect) == 0:
                if not self.in_progress:
                    notify(f"{activity_name}奖励已领完")
                return True
            rect.sort(key=lambda c: c[0])
            x, y, w, h = rect[0]
            scope = sa(((x, y), (x + w, y + h)), top_left)
            self.in_progress = True
            self.ctap(scope)
        else:
            self.scene_graph_step(Scene.INDEX)
