import display, keypad, touchpads, machine, appconfig, audio, sndmixer


vol = machine.nvs_getint('system', 'volume')
if vol == None:
    vol = 128;
    
on = 0x0000FF
off = 0x000000

sndmixer.begin(32)
channels = [None] * 32

button = [[697,1209], [697,1336], [697,1477], [697,1633], [770,1209], [770,1336], [770,1477], [770,1633], [852,1209], [852,1336], [852,1477], [852,1633], [941,1209], [941,1336], [941,1477], [941,1633]]


def on_key(key_index, pressed):
    x, y = key_index % 4, int(key_index / 4)
    if pressed:
        frequency1 = int(button[key_index][0])
        frequency2 = int(button[key_index][1])
        
        synth1 = sndmixer.synth()
        channels[key_index] = synth1
        
        synth2 = sndmixer.synth()
        channels[key_index + 16] = synth2
        
        sndmixer.volume(synth1, vol)
        sndmixer.waveform(synth1, 0)
        
        sndmixer.volume(synth2, vol)
        sndmixer.waveform(synth2, 0)
        
        sndmixer.freq(synth1, frequency1)
        sndmixer.play(synth1)
        sndmixer.freq(synth2, frequency2)
        sndmixer.play(synth2)
        
        display.drawPixel(x, y, on)
        display.flush()
    else:
        if channels[key_index] is not None:
            sndmixer.stop(channels[key_index])
            sndmixer.stop(channels[key_index + 16])
            display.drawPixel(x, y, 0x00)
            display.flush()

keypad.add_handler(on_key)

# volume control
is_down = False;
def vol_up(is_pressed):
    global vol
    if is_pressed:
        vol += 32
        if vol > 255:
            vol = 255
        setvolume(vol)

def vol_down(is_pressed):
    global vol
    if is_pressed:
        vol -= 32
        if vol < 0:
            vol = 0
        setvolume(vol)
        
def setvolume(volume):
    print(volume)
    for index in audio.handles.keys():
        sndmixer.volume(index, volume)


touchpads.on(touchpads.RIGHT, vol_up)
touchpads.on(touchpads.LEFT, vol_down)