# code for magic 8 "ball"

import time, board, digitalio, neopixel, busio, math, adafruit_lis3dh, random
from audiopwmio import PWMAudioOut as AudioOut
from audiocore import WaveFile

RED = (255, 0, 0)
YELLOW = (255, 150, 0)
GREEN = (0, 255, 0)
BLACK = (0,0,0)

#configure the speaker
speaker = digitalio.DigitalInOut(board.SPEAKER_ENABLE)
speaker.direction = digitalio.Direction.OUTPUT
speaker.value = True
audio = AudioOut(board.SPEAKER)

#set path where sound files can be found
path = "magic_box/"


i2c = busio.I2C(board.ACCELEROMETER_SCL, board.ACCELEROMETER_SDA)
int1 = digitalio.DigitalInOut(board.ACCELEROMETER_INTERRUPT)
accelerometer = adafruit_lis3dh.LIS3DH_I2C(i2c, address=0x19, int1 = int1)
accelerometer.range = adafruit_lis3dh.RANGE_8_G

strip_pin = board.A1
strip_num_of_lights = 30
strip = neopixel.NeoPixel(strip_pin, strip_num_of_lights, brightness = 0.5, auto_write = True)

sounds = ["Without_a_Doubt.wav", "It_is_certain.wav", "Ask_again.wav", "Better_not_tell_you_now.wav","My_sources_say_no.wav", "Outlook_not_good.wav"]

def play_sound(filename):
    with open(path + filename, "rb") as wave_file:
        wave = WaveFile(wave_file)
        audio.play(wave)
        while audio.playing:
            pass

def play_random_sound(filename, sound_num):
    with open(path + filename, "rb") as wave_file:
        wave = WaveFile(wave_file)
        audio.play(wave)
        while audio.playing:
            if sound_num ==0:
                strip.fill(GREEN)
            elif random_number ==1:
                strip.fill(GREEN)
            elif random_number ==2:
                strip.fill(YELLOW)
            elif random_number ==3:
                strip.fill(YELLOW)
            elif random_number ==4:
                strip.fill(RED)
            elif random_number ==5:
                strip.fill(RED)


last_random = 10
def random_num(last_random):
    random_number = random.randint(0,5)
    while last_random == random_number:
        random_number = random.randint(0,5)
    last_random = random_number
    return random_number, last_random

while True:
    if accelerometer.shake(shake_threshold=15):
       play_sound("magic-8-ball-sound.wav")
       random_number, last_random = random_num(last_random)
       play_random_sound(sounds[random_number], random_number)
    else:
        strip.fill(BLACK)
