import time
import board
import neopixel
from mpd import MPDClient, CommandError, ConnectionError
import traceback

# === NeoPixel Setup ===
pixel_pin = board.D12
num_pixels = 16
ORDER = neopixel.GRB
pixels = neopixel.NeoPixel(
    pixel_pin, num_pixels, brightness=0.2, auto_write=False, pixel_order=ORDER
)


# === Regenbogen Effekt ===
def wheel(pos):
    if pos < 0 or pos > 255:
        return (0, 0, 0)
    if pos < 85:
        return (int(pos * 3), int(255 - pos * 3), 0)
    if pos < 170:
        pos -= 85
        return (int(255 - pos * 3), 0, int(pos * 3))
    pos -= 170
    return (0, int(pos * 3), int(255 - pos * 3))


def rainbow_cycle(wait):
    for j in range(255):
        for i in range(num_pixels):
            pixel_index = (i * 256 // num_pixels) + j
            pixels[i] = wheel(pixel_index & 255)
        pixels.show()
        time.sleep(wait)


# === MPD Verbindung ===
def get_mpd_state():
    client = MPDClient()
    try:
        client.connect("localhost", 6600)
        status = client.status()
        return status.get("state", "stop")
    except (ConnectionError, CommandError, Exception) as e:
        print(f"[MPD Fehler] {e}")
        traceback.print_exc()
        return "error"
    finally:
        try:
            client.close()
            client.disconnect()
        except:
            pass


# === Haupt-Daemon ===
def main():
    last_play_time = 0
    lights_on = False

    while True:
        state = get_mpd_state()
        now = time.time()

        if state == "play":
            last_play_time = now
            lights_on = True
            rainbow_cycle(0.001)  # schneller Regenbogenzyklus
        else:
            if lights_on and (now - last_play_time > 60):
                pixels.fill((0, 0, 0))
                pixels.show()
                lights_on = False
            else:
                time.sleep(1)  # MPD ist pausiert oder gestoppt, aber innerhalb 60 Sek.

        time.sleep(0.5)  # MPD-Check-Intervall


if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        pixels.fill((0, 0, 0))
        pixels.show()
        print("Beendet.")
