# ======================================================================
# 12회차 | 05 미션 카드 - 마커 보기 (날지 않음)
# ----------------------------------------------------------------------
# 드론 카메라로 마커 카드를 비춰서 번호를 읽는지 확인한다. "Tello" 창에서 q 로 끝.
# 드론은 바닥에 두고(모터 꺼짐) 카드를 카메라 앞에 보여 준다.
#
# 확인할 것
#   - 몇 cm 거리까지 읽히나? (가까이, 멀리 움직여 보기)
#   - 기울이거나, 손가락으로 테두리를 가리면 읽히나?
#   - 크기(area) 숫자는 거리에 따라 어떻게 변하나? 거리가 2배면 크기는?
# ======================================================================

import cv2

from tello import start

tello_id = "TELLO-58C5B7"      # 내 드론 이름으로 바꾸기

aruco = cv2.aruco
dictionary = aruco.getPredefinedDictionary(aruco.DICT_4X4_50)
if hasattr(aruco, "ArucoDetector"):
    detector = aruco.ArucoDetector(dictionary, aruco.DetectorParameters())
else:
    detector = None


def find_markers(frame):
    """[(번호, 크기, 가운데 x, 가운데 y), ...] 와 그리기용 corners, ids"""
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    if detector is not None:
        corners, ids, _ = detector.detectMarkers(gray)
    else:
        corners, ids, _ = aruco.detectMarkers(gray, dictionary)
    found = []
    if ids is not None:
        for c, i in zip(corners, ids.flatten()):
            pts = c.reshape(4, 2)
            cx, cy = pts.mean(axis=0)
            found.append((int(i), cv2.contourArea(pts), int(cx), int(cy)))
    return found, corners, ids


def run():
    if not camera.open():
        print("영상을 받지 못했습니다.")
        return
    print("카드를 카메라 앞에 보여 주세요. q 로 끝")
    last_print = 0
    while True:
        frame = camera.read_fresh()
        if frame is None:
            cv2.waitKey(10)
            continue
        found, corners, ids = find_markers(frame)
        view = frame.copy()
        if ids is not None:
            aruco.drawDetectedMarkers(view, corners, ids)
        for i, area, cx, cy in found:
            cv2.putText(view, f"id {i}  area {area:.0f}", (cx - 60, cy), cv2.FONT_HERSHEY_SIMPLEX,
                        0.8, (0, 0, 255), 2)
        if found and time.time() - last_print > 0.5:
            print("보이는 마커 :", [(i, int(a)) for i, a, _, _ in found])
            last_print = time.time()
        cv2.imshow("Tello", view)
        if cv2.waitKey(1) & 0xFF == ord("q"):
            break
    cv2.destroyAllWindows()


start(tello_id, run)
