import usb_mixer
import board
import adafruit_dotstar
import analogio
import time
import math
import ulab.numpy
import supervisor
import key_interface
import storage

ANALOG_SAMPLE_SIZE=150

pixel = adafruit_dotstar.DotStar(board.DOTSTAR_CLOCK, board.DOTSTAR_DATA, 1)
slider_in = [
    analogio.AnalogIn(board.A0),
    analogio.AnalogIn(board.A1),
    analogio.AnalogIn(board.A2),
    analogio.AnalogIn(board.A3),
    analogio.AnalogIn(board.A4)
]

i2c = board.I2C()
keys = key_interface.KeyInterface(i2c)

slider_vals = [0,0,0,0,0]
buttons = [0,0,0,0,0]

def readSlider(num):
    vals = []
    for i in range(0, ANALOG_SAMPLE_SIZE):
        vals.append((slider_in[num].value / 0xFFFF) * 0xFFF) # Scale analogio back to ADC resolution
    val_median = ulab.numpy.mean(ulab.numpy.ndarray(vals))
    return math.floor((val_median / 0xFFF) * usb_mixer.RESOLUTION)

try:
    pixel.fill((0,0,32))
    while not supervisor.runtime.usb_connected:
        time.sleep(0.5)

    mixer = usb_mixer.UsbMixer()
    pixel.fill((0,32,0))
    while True:
        new_values = [
            readSlider(0),
            readSlider(1),
            readSlider(2),
            readSlider(3),
            readSlider(4)
        ]
        new_buttons = keys.scan()
        if new_values != slider_vals or new_buttons != buttons:
            mixer.send_values(new_values[0], new_values[1], new_values[2], new_values[3], new_values[4], new_buttons)
            pixel.fill((32,32,32))
            slider_vals = new_values
            buttons = new_buttons
            pixel.fill((0,32,0))
        time.sleep(0.001)
except Exception as ex:
    pixel.fill((255,0,0))
    with open("/runtime_ex.txt", "w") as fp:
        fp.write(ex)
    print(ex)