#!/usr/bin/python3

import pygame
import RPi.GPIO as GPIO # Import the Raspberry Pi GPIO Library

#Stores objects with music
sounds = [0,0,0,0] # 4 areas of memory ready for audio objects
pi_pins = [7,11,13,15] # This is the 4 pins we are monitoring for button pushes

def button_callback(channel):
    # Print out the Pi PIN that detected the 3.3V
    # print(channel)
    # Print out the location in the list. Used for music
    pi_pin_index = pi_pins.index(channel)
    print("Button was pushed on PIN:" , channel, "Connected to mixer index ", pi_pin_index, " Press Enter to quit and load Login Prompt. ")
    
    # Make sure all sound is stopped. If someone pushes button during audio from another file
    for sound in sounds:
        sound.stop()
    # Play sound
    sounds[pi_pin_index].play()

# Setup GPIO Board settings
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)

# Set pins to be INPUT and down
for pi_pin in pi_pins:
    GPIO.setup(pi_pin,GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
    # Setup pin event monitoring
    GPIO.add_event_detect(pi_pin,GPIO.RISING,button_callback, bouncetime=1000)

pygame.mixer.init()
# Load in the audio files. We do it this way to make sure we load the 4 into memory and not read the SDCARD every time the audio is changed.

# Load in the WAV audio files. Sound module ONLY supports WAV and not MP3:-(
sounds[0] = pygame.mixer.Sound("/boot/1.wav")
sounds[1] = pygame.mixer.Sound("/boot/2.wav")
sounds[2] = pygame.mixer.Sound("/boot/3.wav")
sounds[3] = pygame.mixer.Sound("/boot/4.wav")

# Pause Script for Input. As everything is a callback function, we only need to wait. 
message = input("Press Enter to stop Audio Button App and cleanup Application. This will load Login prompt:")

GPIO.cleanup()