import serial
import time
import pygame
from pydub import AudioSegment
import serial.tools.list_ports

# Define the paths
#Short notes
NOTES_PATH = "Player\\notes\\mp3-master\\"
#Long notes
#NOTES_PATH = r"C:\Users\Balthazar\Shared\ECAM\Advance Robotique\Project\Player\notes\high-quality-master\renamed\\"
SERIAL_PORT = "COM5" #"COM3"
BAUD_RATE = 115200

# New Features
wait_note_finish = False  # Set to False to play without waiting for the note to finish
keyboard_input = False   # Set to False to disable keyboard note input
check_com3 = True       # Set to False to skip COM3 check

pygame.mixer.init()

octave = 4

notes = ["C", "Db", "D", "Eb", "E", "F", "Gb", "G", "Ab", "A", "Bb", "B"]


def play_note_with_pygame(note):
    try:
        pygame_sound = pygame.mixer.Sound(f"{NOTES_PATH}{note}.mp3")
        pygame_sound.play()
        if wait_note_finish:
            while pygame.mixer.get_busy():  # Wait until sound is finished
                pygame.time.Clock().tick(10)
    except Exception as e:
        print(f"Error playing {note}: {e}")


# Check if COM3 is connected
if check_com3:
    ports = list(serial.tools.list_ports.comports())
    com3_found = any(port.device == SERIAL_PORT for port in ports)
    if not com3_found:
        print(f"{SERIAL_PORT} not found. Switching to keyboard input mode.")
        keyboard_input = True

try:
    ser = serial.Serial(SERIAL_PORT, BAUD_RATE, timeout=1)
    time.sleep(2)
except Exception as e:
    print(f"Error opening {SERIAL_PORT}: {e}")
    keyboard_input = True

print("Listening for Arduino input...")

while True:
    try:
        # Keyboard input for playing notes
        if keyboard_input:
            user_input = input("Enter note (C, Db, D, ... B) or 'q' to quit: ")
            if user_input == 'q':
                break
            if user_input in notes:
                play_note_with_pygame(f"{user_input}{octave}")

        # Arduino input for playing notes
        data = ser.readline().decode('utf-8', errors='ignore').strip()
        if data:
            print("data : " + data)
            note = data
            if note in notes:
                play_note_with_pygame(f"{note}{octave}")

    except KeyboardInterrupt:
        print("Exiting...")
        break

    except Exception as e:
        print(f"Error: {e}")

ser.close()
