try:  #local script
    from lib.datatypes import PictureMatrix, RGB, FusionLightData, FusionLightEffect, FusionLightColor, FusionLightDirection
    from lib.device import get_device
except ImportError:  #as a module
    from .lib.datatypes import PictureMatrix, RGB, FusionLightData, FusionLightEffect, FusionLightColor, FusionLightDirection 
    from .lib.device import get_device

from cv2.typing import MatLike
import sys, cv2

"""
For setting images in / switching between profiles. 
"""

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

#only allow properly supported profile ids since theres not much point in supporting it especially when it gets reset after reboot
#(even though profile ids way higher than this is actually writable and persistent, see set_custom_light_effect comments)
try:
    profile = int(sys.argv[1])
    if profile not in range(5):
        raise TypeError()
except:
    print('Invalid profile given (must be from 0-4).')
    exit(-1)

dev = get_device()

if len(sys.argv) > 2:
    #load a new image
    def set_image(raw: MatLike) -> None:
        pre = cv2.resize(raw, (19, 6), interpolation=cv2.INTER_AREA)
        im = cv2.cvtColor(pre, cv2.COLOR_BGR2RGB)

        pixels = []

        h, w, _ = im.shape

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

        #adjustment needed to give true colors (maybe it's just my keyboard)
        dev.set_custom_light_effect(profile, PictureMatrix.pixel_matrix_to_keys(pixels), adjust=dev.ADJUST_RGB)

    set_image(cv2.imread(sys.argv[2]))
else:
    #at runtime this would not reload if we dont set_custom_light_effect so we need to do it anyways
    #(unless we are not in any of the custom profiles then the last image will show up right when we do set_simple_light_effect)
    load = PictureMatrix.from_bytes(dev.get_custom_light_effect(profile))
    dev.set_custom_light_effect(profile, load)

dev.set_simple_light_effect(FusionLightData(FusionLightEffect.Custom1 + profile, 1, 255, FusionLightColor.White, FusionLightDirection.Left2Right))