from fusion.datatypes import *
from fusion.device import get_device
from cv2.typing import MatLike
import sys, cv2

if len(sys.argv) < 2:
    print(f'Usage: {__file__} <image/video path> [profile id]')
    exit(-1)

if len(sys.argv) >= 3:
    try:
        profile = int(sys.argv[3])
        if profile not in range(5):
            raise TypeError()
    except:
        print('Invalid profile id given, defaulting to 1...')
        profile = 1
else:
    profile = 1


dev = get_device()

#change to profile for the image stream first
dev.set_simple_light_effect(FusionLightData(int(FusionLightEffect.Custom1) + profile - 1, 0, 255, FusionLightColor.Random, 0))


def set_image(raw: MatLike) -> None:
    pre = cv2.resize(raw, (19, 6), interpolation=cv2.INTER_AREA)
    im = cv2.cvtColor(pre, cv2.COLOR_BGR2RGB)

    #display what's supposed to be encoded in the keyboard at this frame
    cv2.imshow('preview', cv2.resize(pre, (190*5, 60*5)))
    cv2.waitKey(1)

    pixels = []

    h, w, _ = im.shape

    for y in range(h):
        for x in range(w):
            pixels.append(RGB(*im[y, x]))

    dev.set_custom_light_effect(profile, PictureMatrix.pixel_matrix_to_keys(pixels))



#apparently also works with static images
vid = cv2.VideoCapture(sys.argv[1])

#skip some frames so it's not too slow
interval = vid.get(cv2.CAP_PROP_FPS) // 4

count = 0
while vid.isOpened():
    ret, frame = vid.read()
    if ret:
        set_image(frame)
        count += interval
    else:
        vid.release()
        break

#keep last frame until we manually quit
cv2.waitKey(0)




