import os
import signal
import subprocess

MUSIC_DIR = "/home/arduino/music_player/mp3"

if not os.path.exists(MUSIC_DIR):
    print(f"Error: Directory {MUSIC_DIR} does not exist!")
    exit(1)

# Scan and sort all MP3 files
playlist = [f for f in os.listdir(MUSIC_DIR) if f.lower().endswith(".mp3")]
playlist.sort()

if not playlist:
    print(f"Notice: Please upload .mp3 files to {MUSIC_DIR} first!")
    exit(1)

player_proc = None
current_index = 0
is_paused = False

def stop_current():
    """Safely terminates the active audio child process"""
    global player_proc, is_paused
    if player_proc and player_proc.poll() is None:
        player_proc.terminate()
        player_proc.wait()
    player_proc = None
    is_paused = False

def play_track(index):
    """Switches to and plays the track at the specified index"""
    global player_proc, current_index, is_paused
    stop_current()
    current_index = index % len(playlist)
    file_path = os.path.join(MUSIC_DIR, playlist[current_index])

    # Spawn background mpg123 process for streaming playback
    player_proc = subprocess.Popen(
        ["mpg123", "-q", file_path],
        stdout=subprocess.DEVNULL,
        stderr=subprocess.DEVNULL
    )
    is_paused = False
    print(f"\n▶ Now Playing [{current_index + 1}/{len(playlist)}]: {playlist[current_index]}")

def toggle_pause():
    """Toggles pause/resume using native Linux process signals"""
    global player_proc, is_paused
    if not player_proc or player_proc.poll() is not None:
        return

    if not is_paused:
        # Send SIGSTOP to freeze the child process
        os.kill(player_proc.pid, signal.SIGSTOP)
        is_paused = True
        print("⏸ Paused")
    else:
        # Send SIGCONT to resume the child process
        os.kill(player_proc.pid, signal.SIGCONT)
        is_paused = False
        print("▶ Resumed")

print("=" * 50)
print("       Uno Q USB Music Player (Terminal Edition)")
print("=" * 50)
print("Track List:")
for i, song in enumerate(playlist):
    print(f"  [{i + 1}] {song}")
print("-" * 50)
print("Controls: [p] Pause/Resume | [n] Next | [b] Previous | [Number] Jump | [q] Quit")
print("=" * 50)

# Automatically start the first track upon launch
play_track(0)

# Interactive control loop
while True:
    try:
        cmd = input("\nEnter command: ").strip().lower()
        if cmd == 'q':
            stop_current()
            print("Player exited safely.")
            break
        elif cmd == 'p':
            toggle_pause()
        elif cmd == 'n':
            play_track(current_index + 1)
        elif cmd == 'b':
            play_track(current_index - 1)
        elif cmd.isdigit():
            idx = int(cmd) - 1
            if 0 <= idx < len(playlist):
                play_track(idx)
            else:
                print("Invalid track number!")
        else:
            print("Invalid input. Options: p / n / b / Track Number / q")
    except (KeyboardInterrupt, EOFError):
        stop_current()
        break