import RPi.GPIO as GPIO  
import time  
import random
import os

GPIO.cleanup()
GPIO.setmode(GPIO.BCM)  

left = 20
right = 21
GPIO.setup(left, GPIO.OUT) 
GPIO.setup(right, GPIO.OUT) 



def turnLeft():

    print("Left!")
    GPIO.output(left, GPIO.LOW)  
    time.sleep(2)
    GPIO.output(left, GPIO.HIGH)


def turnRight():
    print("Right!")
    GPIO.output(right, GPIO.LOW)  
    time.sleep(2)
    GPIO.output(right, GPIO.HIGH)

def forward():

    print("Forward!")
    GPIO.output(left, GPIO.LOW)  
    GPIO.output(right, GPIO.LOW)

    time.sleep(2)  

    GPIO.output(left, GPIO.HIGH)  
    GPIO.output(right, GPIO.HIGH)  

def playAudio():
    # Collect all the names of the images in out folder and the amount
    names = [name for name in os.listdir('/home/pi/Desktop/moomba/audio')]
    total = len([name for name in os.listdir('/home/pi/Desktop/moomba/audio')])

    # Generate a random number, -1 because our index start at 0
    randomInt = random.randint(0, total-1)
    print(total)

    # Fetch the name belonging to this random number
    name = '/home/pi/Desktop/moomba/audio/'+names[randomInt]
    print(name)

    #Play the audio
    os.system('mpg123 ' + name)
    time.sleep(0.2)

def turnOff():
    print('Off')
    GPIO.output(left, GPIO.HIGH)  
    GPIO.output(right, GPIO.HIGH)  

while True:

    actionInt = random.randint(0,3) 

    if actionInt == 0:
        forward()
    elif actionInt == 1:
        turnRight()
    elif actionInt == 2:
        turnLeft()
    elif actionInt == 3:
        playAudio()

    time.sleep(2)
