import board, audiomixer, digitalio, adafruit_mpr121, adafruit_vl53l1x
from audiomp3 import MP3Decoder

min_dist=0
max_dist=200
min_vol=0.1
max_vol=1.0

# Setup I2C and devices
i2c = board.I2C()
distance_sensor = adafruit_vl53l1x.VL53L1X(i2c)
touchpad = adafruit_mpr121.MPR121(i2c)

# Import error handling for audio output !
try:
    from audioio import AudioOut
except ImportError:
    try:
        from audiopwmio import PWMAudioOut as AudioOut
    except ImportError:
        print("This board does not support audio")

# Setup speaker
speaker = digitalio.DigitalInOut(board.SPEAKER_ENABLE)
speaker.direction = digitalio.Direction.OUTPUT
speaker.value = True
audio = AudioOut(board.SPEAKER)

# Define folder path and notes
path = "klezmernotes/"
notes = ["1D.mp3", "2Eb.mp3", "3F#.mp3", "4G.mp3", "5A.mp3", "6Bb.mp3", "7C.mp3", "8D(top).mp3"]

# Setup mixer with initial volume
mixer = audiomixer.Mixer(voice_count=1, sample_rate=44100, channel_count=1,
                         bits_per_sample=16, samples_signed=True)
audio.play(mixer)

# Function to map distance to volume level
def map_distance_to_volume(distance):
    if distance:
        distpercent = distance / max_dist
        volume = min(1.0, max(0.0, distpercent))  # Limits volume to range [0, 1]
        return volume
    else:
        return 0.5

# Function to play sound with volume control
def play_sound(filename, volume):
    mp3_file = open(path + filename, "rb")
    decoder = MP3Decoder(mp3_file)
    mixer.stop_voice(0)  # Stop any sound already playing on voice 0
    mixer.voice[0].play(decoder, loop=False)
    mixer.voice[0].level = volume  # Set mixer volume
    while mixer.voice[0].playing:
        if not touchpad[i].value:
            mixer.stop_voice(0)
    mp3_file.close()

while True:
    # Read distance and set volume
    distance_sensor.start_ranging()
    distance = distance_sensor.distance
    distance_sensor.stop_ranging()
    volume = map_distance_to_volume(distance)
    for i in range(12):
        if touchpad[i].value and i < len(notes):
            print(f"Touchpad {i} pressed! Playing {notes[i]} at volume {volume}")
            play_sound(notes[i], volume)
            print("Sound played!")