from adafruit_macropad import MacroPad
import usb_cdc, asyncio, random

macropad = MacroPad()
macropad.pixels.brightness = 0.3
color = 0xad20b4

async def get_key(taskslist):
    while True:
        key_event = macropad.keys.events.get()
        if key_event:
            if key_event.pressed:
                print("key k:{} t:{}".format(key_event.key_number, len(taskslist)))
                taskslist.append(asyncio.create_task(blink(key_event.key_number)))
        await asyncio.sleep(0)

async def blink(led):
    timer = random.random() * 3
    for _ in range(5):
        macropad.pixels[led] = color
        await asyncio.sleep(timer)
        macropad.pixels[led] = 0x0
        await asyncio.sleep(timer)

async def manage_tasks(taskslist):
    tasks = 0
    print("Run task manager  t:{}".format(len(taskslist)))
    while True:
        for task_number in range(0, len(taskslist)):
            if taskslist[task_number].done():
                print("Remove task t:{}/{}".format(task_number + 1,len(taskslist)))
                taskslist.pop(task_number)
                break
        await asyncio.sleep(0)

async def main():
    tasks = []
    tasks.append(asyncio.create_task(get_key(tasks)))
    tasks.append(asyncio.create_task(manage_tasks(tasks)))
    await asyncio.gather(*tasks)

asyncio.run(main())
