import cv2

from mower.utils import config
from mower.utils.image import cropimg, loadres
from mower.utils.vector import va

clue_size = (162, 216)
clue_top_left = {
    "daily": (1118, 334),
    "receive": (1305, 122),
    "give_away": (30, 208),
    # 摆放线索界面，线索框的左上角
    1: (72, 228),
    2: (374, 334),
    3: (679, 198),
    4: (1003, 265),
    5: (495, 660),
    6: (805, 573),
    7: (154, 608),
}
dot_offset = (168, -8)
main_offset = (425, 0)
main_time_offset = (443, 257)


def tl2p(top_left):
    return top_left, va(top_left, clue_size)


def is_orange(dot):
    orange_dot = (255, 104, 1)
    return all([abs(dot[i] - orange_dot[i]) < 3 for i in range(3)])


clue_scope = {}
for index, top_left in clue_top_left.items():
    clue_scope[index] = tl2p(top_left)
clue_dots = {}
main_dots = {}
main_time = {}
main_scope = {}
for i in range(1, 8):
    clue_dots[i] = va(clue_top_left[i], dot_offset)
    main_dots[i] = va(clue_dots[i], main_offset)
    main_time[i] = va(clue_top_left[i], main_time_offset)
    main_scope[i] = tl2p(va(clue_top_left[i], main_offset))
tm_thres = 0.6
exit_pos = (1239, 144)


def clue_cls(scope):
    scope_dict = clue_scope if isinstance(scope, str) else main_scope
    img = cropimg(config.recog.img, scope_dict[scope])
    for i in range(1, 8):
        res = loadres(f"clue/{i}")
        result = cv2.matchTemplate(img, res, cv2.TM_CCOEFF_NORMED)
        min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
        if max_val > tm_thres:
            return i
    return None
