# ======================================================================
# 07회차 | 11 도전 - 조종을 녹화해서 되풀이 (pygame 필요)
# ----------------------------------------------------------------------
# 1. 키보드로 조종한다. (10번 파일과 같은 키) 이륙한 순간부터 착륙할 때까지
#    "몇 초에 어떤 rc 값으로 바꿨는지" 가 기록된다.
# 2. ESC 로 창을 닫으면, 기록한 비행을 그대로 되풀이할지 묻는다.
# 3. y 를 누르면 다시 이륙해서 기록대로 혼자 난다.
#
# 기록 모양 : [(0.0, (0,0,0,0)), (1.2, (0,40,0,0)), (2.7, (0,0,0,0)), ...]
#             (이륙 후 몇 초, rc 값)
#
# 알게 되는 것
#   - 조종 = rc 값을 시간에 따라 바꾸는 것. 그러니 시간과 값만 기록하면 똑같이 재생할 수 있다.
#   - 그런데 되풀이한 비행은 처음과 똑같은 곳에 착륙할까?
#     (바닥 무늬, 배터리, 바람에 따라 조금씩 다르다 -> 착륙 위치를 재서 비교)
#   - 그래서 다음 회차부터 센서를 보고 스스로 고치는 비행을 배운다.
#
# ※ 최대 60초까지 기록한다.
# ======================================================================

import threading

import pygame

from tello import start

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

SPEED = 40
YAW_SPEED = 50
MAX_RECORD = 60                # 최대 기록 시간 (초)


def replay(events):
    """기록(events)대로 다시 날기"""
    print(f"되풀이 시작 : {len(events)}개 기록, {events[-1][0]:.1f}초")
    takeoff()
    t0 = time.time()
    current = (0, 0, 0, 0)
    i = 0
    while True:
        t = time.time() - t0
        while i < len(events) and events[i][0] <= t:
            current = events[i][1]
            i += 1
        if t > events[-1][0]:
            break
        rc(*current)
        time.sleep(0.05)
    stop()
    hover(1)
    land()
    print("되풀이 끝! 처음 착륙한 곳과 비교해 보세요.")


def run():
    pygame.init()
    screen = pygame.display.set_mode((560, 320))
    pygame.display.set_caption("녹화 조종기 - T 이륙(녹화 시작) / L 착륙(녹화 끝) / ESC")
    font = pygame.font.SysFont("malgungothic", 22)
    clock = pygame.time.Clock()

    events = []                                     # 기록
    rec = {"on": False, "t0": 0.0}
    busy = [None]

    def do_takeoff():
        takeoff()
        events.clear()
        rec["t0"] = time.time()
        rec["on"] = True
        events.append((0.0, (0, 0, 0, 0)))

    def do_land():
        if rec["on"]:
            events.append((time.time() - rec["t0"], (0, 0, 0, 0)))
            rec["on"] = False
        stop()
        land()

    def do(f):
        if busy[0] and busy[0].is_alive():
            return
        busy[0] = threading.Thread(target=f, daemon=True)
        busy[0].start()

    last_cmd, last_send = None, 0
    running = True
    while running:
        for e in pygame.event.get():
            if e.type == pygame.QUIT:
                running = False
            elif e.type == pygame.KEYDOWN:
                if e.key == pygame.K_ESCAPE:
                    running = False
                elif e.key == pygame.K_t:
                    do(do_takeoff)
                elif e.key == pygame.K_l:
                    do(do_land)

        k = pygame.key.get_pressed()
        lr = fb = ud = yw = 0
        if k[pygame.K_w]: fb += SPEED
        if k[pygame.K_s]: fb -= SPEED
        if k[pygame.K_a]: lr -= SPEED
        if k[pygame.K_d]: lr += SPEED
        if k[pygame.K_UP]: ud += SPEED
        if k[pygame.K_DOWN]: ud -= SPEED
        if k[pygame.K_LEFT]: yw -= YAW_SPEED
        if k[pygame.K_RIGHT]: yw += YAW_SPEED
        cmd = (lr, fb, ud, yw)

        now = time.time()
        moving = busy[0] is not None and busy[0].is_alive()
        if not moving and ((cmd != last_cmd and now - last_send > 0.05) or now - last_send > 0.3):
            rc(*cmd)
            if rec["on"] and cmd != last_cmd:
                events.append((now - rec["t0"], cmd))
            last_cmd, last_send = cmd, now

        if rec["on"] and now - rec["t0"] > MAX_RECORD:
            print(f"{MAX_RECORD}초가 지나서 녹화를 끝내고 착륙합니다.")
            do(do_land)

        rec_time = now - rec["t0"] if rec["on"] else 0
        lines = [
            "T 이륙(녹화 시작)   L 착륙(녹화 끝)   ESC 끝내기",
            "W/S 앞/뒤   A/D 옆   ↑/↓ 위/아래   ←/→ 회전",
            "",
            f"녹화 {'중 ' + format(rec_time, '.1f') + '초' if rec['on'] else '꺼짐'}    기록 {len(events)}개",
            f"rc {cmd}",
        ]
        screen.fill((35, 20, 20) if rec["on"] else (25, 25, 35))
        for i, text in enumerate(lines):
            screen.blit(font.render(text, True, (255, 220, 120)), (20, 20 + i * 50))
        pygame.display.flip()
        clock.tick(30)

    stop()
    pygame.quit()
    if busy[0] and busy[0].is_alive():
        busy[0].join()
    if rec["on"]:                                   # 착륙 안 하고 ESC 를 눌렀으면
        do_land()

    if len(events) < 2:
        print("기록이 없어서 되풀이하지 않습니다.")
        return
    print("기록 :", [(round(t, 1), c) for t, c in events])
    if input("기록한 비행을 되풀이할까요? 드론을 출발점에 다시 놓고 y : ").strip().lower() == "y":
        replay(events)


start(tello_id, run)
