import cv2
import json
import numpy as np

# --- KONFIGURASI AWAL ---
SCALER = 40 
BOX_W = int(20 * SCALER)   # 800 pixel
BOX_H = int(5.7 * SCALER) # 228 pixel

offset_x, offset_y = 255, 385 
rotation_state = 2 

titik_relatif = [] 
max_titik = 60      # 15 soal x 4 pilihan

def click_event(event, x, y, flags, params):
    global titik_relatif
    if event == cv2.EVENT_LBUTTONDOWN:
        if offset_x <= x <= offset_x + BOX_W and offset_y <= y <= offset_y + BOX_H:
            if len(titik_relatif) < max_titik:
                rel_x = x - offset_x
                rel_y = y - offset_y
                titik_relatif.append((rel_x, rel_y))
                print(f"Titik {len(titik_relatif)} disimpan (Relatif: {rel_x},{rel_y})")
            
            if len(titik_relatif) == max_titik:
                # Simpan standar offset 100,20 agar sinkron dengan scanner
                save_data = [(pt[0] + 100, pt[1] + 20) for pt in titik_relatif]
                with open('kunci_statis.json', 'w') as f:
                    json.dump(save_data, f)
                print("\nKALIBRASI SELESAI! File 'kunci_statis.json' tersimpan.")

cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1280)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 720)

while True:
    success, frame = cap.read()
    if not success: break

    # --- FITUR ROTATE ---
    if rotation_state == 1:
        frame = cv2.rotate(frame, cv2.ROTATE_90_CLOCKWISE)
    elif rotation_state == 2:
        frame = cv2.rotate(frame, cv2.ROTATE_180)
    elif rotation_state == 3:
        frame = cv2.rotate(frame, cv2.ROTATE_90_COUNTERCLOCKWISE)

    img = frame.copy()

    # --- GAMBAR KOTAK & TITIK ---
    cv2.rectangle(img, (offset_x, offset_y), (offset_x + BOX_W, offset_y + BOX_H), (255, 0, 0), 2)
    
    for rel_pt in titik_relatif:
        abs_x = offset_x + rel_pt[0]
        abs_y = offset_y + rel_pt[1]
        cv2.circle(img, (abs_x, abs_y), 4, (0, 255, 0), -1)

    # --- UI INFORMASI DENGAN BACKGROUND HITAM ---
    count = len(titik_relatif)
    soal_skrg = (count // 4) + 1
    pilihan = ['A', 'B', 'C', 'D'][count % 4] if count < max_titik else "SELESAI"
    
    # 1. Background untuk Label Soal (di atas kotak)
    text_soal = f"Klik Soal {soal_skrg} [{pilihan}]"
    cv2.rectangle(img, (offset_x, offset_y - 35), (offset_x + 300, offset_y), (0, 0, 0), -1)
    cv2.putText(img, text_soal, (offset_x + 5, offset_y - 10), 
                cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 255), 2)

    # 2. Background untuk Status Kontrol (di pojok kiri bawah)
    cv2.rectangle(img, (0, 680), (450, 720), (0, 0, 0), -1)
    cv2.putText(img, f"Pos: {offset_x},{offset_y} | Rot: {rotation_state*90}deg | Q: Exit", (10, 705), 
                cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 1)

    cv2.imshow("Kalibrasi Interaktif", img)
    cv2.setMouseCallback("Kalibrasi Interaktif", click_event)

    # --- LOGIKA TOMBOL ---
    key = cv2.waitKey(1) & 0xFF
    if key == ord('q'): break
    elif key == ord('w'): offset_y -= 5
    elif key == ord('s'): offset_y += 5
    elif key == ord('a'): offset_x -= 5
    elif key == ord('d'): offset_x += 5
    elif key == ord('r'): rotation_state = (rotation_state + 1) % 4
    elif key == ord('c'): titik_relatif = []

    if len(titik_relatif) == max_titik:
        cv2.waitKey(2000) 
        break

cap.release()
cv2.destroyAllWindows()