import os, sys, io, csv
from gpiozero import LED, PWMLED, Button, LEDBoard, LEDCharDisplay, LEDMultiCharDisplay, LEDCharFont

sf2_dir = "./sf2/"  # Dir where SoudFonts are loaded from
sessions_dir = "./sessions/"  # Dir where Sessions will be exported / imported

# Read GPIO Settings from gpio.csv
with open('./gpio.csv', mode='r', encoding='utf-8') as file:
    reader = csv.DictReader(file)
    for row in reader:
        if row['Function'] != "":
            exec(f"{row['Function']} = {row['GPIONumber']}")  # Assign 'GPIONumber' like value to the variables 'Function'

# New characters to Font
my_font = LEDCharFont({
    ' ': (0, 0, 0, 0, 0, 0, 0),
    'o': (0, 0, 1, 1, 1, 0, 1),
    '0': (1, 1, 1, 1, 1, 1, 0),
    '1': (0, 1, 1, 0, 0, 0, 0),
    '2': (1, 1, 0, 1, 1, 0, 1),
    '3': (1, 1, 1, 1, 0, 0, 1),
    '4': (0, 1, 1, 0, 0, 1, 1),
    '5': (1, 0, 1, 1, 0, 1, 1),
    '6': (1, 0, 1, 1, 1, 1, 1),
    '7': (1, 1, 1, 0, 0, 0, 0),
    '8': (1, 1, 1, 1, 1, 1, 1),
    '9': (1, 1, 1, 1, 0, 1, 1),
    '+': (1, 0, 0, 0, 0, 0, 0),
    '-': (0, 0, 0, 0, 0, 0, 1),
    '_': (0, 0, 0, 1, 0, 0, 0),
    '=': (1, 0, 0, 1, 0, 0, 0),
    'C': (1, 0, 0, 1, 1, 1, 0),
    'c': (1, 1, 1, 1, 0, 0, 0),
    '¡': (0, 0, 0, 0, 1, 1, 0),
    '!': (0, 1, 1, 0, 0, 0, 0)
})

# Buttons, Leds and 8-Segments Display
debounce_length = 0.05  # Length in seconds of button debounce period
display = LEDMultiCharDisplay(LEDCharDisplay(disp8seg_a, disp8seg_b, disp8seg_c, disp8seg_d, disp8seg_e, disp8seg_f, disp8seg_g, dp=disp8seg_dp, font=my_font, active_high=False), disp8seg_dig1, disp8seg_dig2)
PLAYLEDR = (PWMLED(play_led_red, active_high=False))
PLAYLEDG = (PWMLED(play_led_green, active_high=False))
RECLEDR = (PWMLED(rec_led_red, active_high=False))
RECLEDG = (PWMLED(rec_led_green, active_high=False))
UNDOLEDR = (PWMLED(undo_led_red, active_high=False))
UNDOLEDG = (PWMLED(undo_led_green, active_high=False))
RECBUTTON = (Button(rec_button, bounce_time=debounce_length))
PLAYBUTTON = (Button(play_button, bounce_time=debounce_length))
UNDOBUTTON = (Button(undo_button, bounce_time=debounce_length))
PREVBUTTON = (Button(prev_button, bounce_time=debounce_length))
NEXTBUTTON = (Button(next_button, bounce_time=debounce_length))
MODEBUTTON = (Button(mode_button, bounce_time=debounce_length))

RECBUTTON.hold_time = 0.5
PLAYBUTTON.hold_time = 0.5
UNDOBUTTON.hold_time = 0.5
PREVBUTTON.hold_time = 0.5
NEXTBUTTON.hold_time = 0.5
MODEBUTTON.hold_time = 3.0

# Get a list of all files in the directory ./sf2
def list_sf2():
    sf2_list = sorted(
        [f for f in os.listdir(sf2_dir)
        if os.path.isfile(os.path.join(sf2_dir, f)) and f.lower().endswith('.sf2')])  # Put all the detected files alphabetically on an array
    print("List of all files in the directory ", sf2_dir)
    print(*sf2_list, sep="\n")
    print("\n")
    return sf2_list

# Get a list of all the Sessions Exported on directory ./sessions
def list_sessions(SessionSel):
    sessions_list = sorted(
        [f for f in os.listdir(sessions_dir)
         if os.path.isfile(os.path.join(sessions_dir, f)) and f.lower().endswith('.wav')])  # Put all the detected files alphabetically on an array
    if len(sessions_list) > 0:
        # Group by first 27 characters
        grouped_sessions = {}
        for file in sessions_list:
            key = file[:27]
            if key not in grouped_sessions:
                grouped_sessions[key] = []
            grouped_sessions[key].append(file)
        sessions = sorted(grouped_sessions.keys(), reverse=True)
        selected_session = grouped_sessions[sessions[SessionSel]]
        print(f"-----= List of all exported sessions in the directory: {sessions_dir}")
        print(*sessions, sep="\n")
        print(f"-----= Selected Session: {SessionSel}")
        print(*selected_session, sep="\n")
        print("\n")
    else:
        print("No Exported Sessions found on dir ", str(sessions_dir), '\n')
    return selected_session, sessions