import os
import tkinter as tk
from tkinter import messagebox
import pygame

# ==================== Path Configuration ====================
# Specify the folder path here (supports both Windows and Linux formats)
# If left as None or "", the program defaults to the directory containing this script
CUSTOM_DIR = "/home/arduino/music_player/mp3"

# Example: r"C:\Users\Admin\Music" or "/home/arduino/music"

if CUSTOM_DIR and os.path.exists(CUSTOM_DIR):
    MUSIC_DIR = CUSTOM_DIR
else:
    MUSIC_DIR = os.path.dirname(os.path.abspath(__file__))

# Scan and sort MP3 files
playlist = [f for f in os.listdir(MUSIC_DIR) if f.lower().endswith(".mp3")]
playlist.sort()

current_index = 0
is_paused = False

# Initialize the pygame mixer audio module
pygame.mixer.init()

# ==================== Playback Control Logic ====================
def play_music():
    global is_paused
    if not playlist:
        return

    track_path = os.path.join(MUSIC_DIR, playlist[current_index])
    try:
        pygame.mixer.music.load(track_path)
        pygame.mixer.music.play()
        is_paused = False

        status_label.config(text=f"Playing: {playlist[current_index]}")
        btn_pause.config(text="Pause")

        listbox.selection_clear(0, tk.END)
        listbox.selection_set(current_index)
        listbox.see(current_index)
    except Exception as e:
        messagebox.showerror("Playback Error", f"Cannot play file: {e}")

def toggle_pause():
    global is_paused
    if not playlist:
        return

    if is_paused:
        pygame.mixer.music.unpause()
        is_paused = False
        btn_pause.config(text="Pause")
        status_label.config(text=f"Playing: {playlist[current_index]}")
    else:
        pygame.mixer.music.pause()
        is_paused = True
        btn_pause.config(text="Resume")
        status_label.config(text=f"Paused: {playlist[current_index]}")

def prev_music():
    global current_index
    if not playlist:
        return
    current_index = (current_index - 1) % len(playlist)
    play_music()

def next_music():
    global current_index
    if not playlist:
        return
    current_index = (current_index + 1) % len(playlist)
    play_music()

def on_select(event):
    global current_index
    selection = listbox.curselection()
    if selection:
        current_index = selection[0]
        play_music()

def on_close():
    pygame.mixer.music.stop()
    root.destroy()

# ==================== GUI Construction ====================
root = tk.Tk()
root.title("Music Player")
root.geometry("450x400")
root.protocol("WM_DELETE_WINDOW", on_close)

# Path and status header
path_label = tk.Label(root, text=f"Directory: {MUSIC_DIR}", fg="gray", wraplength=420, font=("Arial", 8))
path_label.pack(pady=(6, 0))

status_label = tk.Label(root, text="Ready", wraplength=420, font=("Arial", 10, "bold"), pady=6)
status_label.pack()

# Track list container
frame_list = tk.Frame(root)
frame_list.pack(fill=tk.BOTH, expand=True, padx=15, pady=5)

scrollbar = tk.Scrollbar(frame_list)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)

listbox = tk.Listbox(frame_list, yscrollcommand=scrollbar.set, font=("Arial", 9), selectmode=tk.SINGLE)
listbox.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
scrollbar.config(command=listbox.yview)

for song in playlist:
    listbox.insert(tk.END, song)

listbox.bind("<Double-Button-1>", on_select)

# Control button panel
frame_ctrl = tk.Frame(root, pady=10)
frame_ctrl.pack()

btn_prev = tk.Button(frame_ctrl, text="Prev", width=8, command=prev_music)
btn_prev.grid(row=0, column=0, padx=5)

btn_play = tk.Button(frame_ctrl, text="Play", width=8, command=play_music)
btn_play.grid(row=0, column=1, padx=5)

btn_pause = tk.Button(frame_ctrl, text="Pause", width=8, command=toggle_pause)
btn_pause.grid(row=0, column=2, padx=5)

btn_next = tk.Button(frame_ctrl, text="Next", width=8, command=next_music)
btn_next.grid(row=0, column=3, padx=5)

if not playlist:
    status_label.config(text="No .mp3 files found in this directory")
else:
    listbox.selection_set(0)

root.mainloop()