import RPi.GPIO as GPIO
import time
from lib.mqtt import create_client, control_player, create_config, check_current_status, check_current_disc, update_disc

client = create_client()

create_config(client)

# Set up GPIO pins for each button
BUTTON_PINS = [17, 18, 27]  # Replace with your GPIO pin numbers

GPIO.setmode(GPIO.BCM)  # Use BCM numbering

# Set up each button pin as input with internal pull-up resistors
for pin in BUTTON_PINS:
    GPIO.setup(pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)

# Callback functions to handle button presses
def button_callback_1(channel):
    client = create_client()
    if check_current_status(client) == "PLAY":
        print("Button 1 pressed! Pausing playback.")
        control_player(client, "PAUSE")
    else:
        print("Button 1 pressed! Playing.")
        control_player(client, "PLAY")

def button_callback_2(channel):
    print("Button 2 pressed!")
    client = create_client()
    control_player(client, "SKIP")
    control_player(client, "PLAY")

# Handling button 3 with a hold check
def button_callback_3(channel):
    start_time = time.time()
    client = create_client()    
    # Wait until the button is released or held for more than 3 seconds
    while GPIO.input(BUTTON_PINS[2]) == GPIO.LOW:  # Button is pressed (active low)
        if time.time() - start_time >= 3:  # Check if 3 seconds have passed
            print("Button 3 held for 3 seconds! Sending RADIO2.")
            disc_data = check_current_disc(client)
            update_disc(client, f"ytube:{disc_data['name']}:{disc_data['type']}:RESET")
            update_disc(client, f"ytube:{disc_data['name']}:{disc_data['type']}:{disc_data['id']}")
            return  # Exit after sending RADIO2
    
    # If button was not held for 3 seconds, send RADIO
    print("Button 3 pressed briefly! Sending RADIO.")
    control_player(client, "RADIO")

# Add event detection for each button press
GPIO.add_event_detect(BUTTON_PINS[0], GPIO.FALLING, callback=button_callback_1, bouncetime=200)
GPIO.add_event_detect(BUTTON_PINS[1], GPIO.FALLING, callback=button_callback_2, bouncetime=200)
GPIO.add_event_detect(BUTTON_PINS[2], GPIO.FALLING, callback=button_callback_3, bouncetime=200)

try:
    # Keep the script running to detect button presses
    while True:
        time.sleep(1)  # Sleep to reduce CPU usage
except KeyboardInterrupt:
    pass
finally:
    GPIO.cleanup()  # Clean up GPIO on exit