import os, machine, display, keypad, audio, random, virtualtimers as vt

col_on = 0x444444
col_off = 0x000000
col_error = 0x990000

# min. interval between re-presses
pI = 200

try:
    directory = '/'.join(__file__.split('/')[:-1])
except:
    directory = '/apps/bubblewrap'

print('directory: ', directory)

def playbackFinished():
    if len(playing) > 0:
        key = playing.pop(0)
        x, y = key % 4, int(key / 4)
        display.drawPixel(x, y, col_on)
        display.flush()
    return 0
        

def on_key(key_index, pressed):
    x, y = key_index % 4, int(key_index / 4)
    if pressed and key_index not in playing:
        display.drawPixel(x, y, col_off)
        display.flush()
        sample = random.randint(0, numSamples-1)

        try:
            print('Playing %s' % samples[sample])
            player = audio.play(samples[sample])
        except BaseException as e:
            player = None
            import sys, system
            sys.print_exception(e)
            system.crashedWarning()

        if player is None or player < 1:
            display.drawPixel(x, y, col_error)
            display.flush()
        else:
            playing.append(key_index)
            vt.new(pI, playbackFinished)


try:
    samples = [filename for filename in os.listfiles(directory, return_full=True) if
        '/._' not in filename and
        (filename.lower().endswith('mp3'))]
except:
    samples = []

print('Samples: %s' % str(samples))
numSamples = len(samples)

playing = []

vt.begin()
keypad.add_handler(on_key)

display.drawFill(col_on)
display.flush()