import os
from os.path import isfile, join
import pygame

# from storage_media import USBDeviceHandler

# import time
# import signal
# import keyboard



dir_path = os.getcwd()
sound_dir = os.getcwd() + "/sounds"
contentlist = os.listdir(sound_dir)
sound_array = []
cut_current_sound = False
channel = False
current_sound_index = -1

contentlist = sorted(contentlist)
# usb_handler = USBDeviceHandler()


def setup_sounds():
    for content in contentlist:
        if isfile(join(sound_dir, content)):
            if content.endswith(".mp3") or content.endswith(".wav"):
                sound = pygame.mixer.Sound(join(sound_dir, content))
                sound_array.append(sound)
                print(content)
    print(sound_array)


def play_sound(index):
    global cut_current_sound
    global current_sound_index
    global channel

    if not cut_current_sound:
        current_sound_index = index
        channel = sound_array[current_sound_index].play()
        while channel.get_busy():
            pygame.time.wait(100)  # ms
            print("Playing...")
            pygame.event.clear()
        print("Finished.")

    """ todo
    make sounds stop when new key pressed
    
    else:
        if current_sound_index == index:
            current_sound_index = index
            channel = sound_array[current_sound_index].play()
            while channel.get_busy():
                pygame.time.wait(100)  # ms
                print("Playing...pygame.init()")
            print("Finished.")
        else:
            print("STOP.")
            
    """

pygame.init()
clock = pygame.time.Clock()
setup_sounds()

run = True
while run:
    clock.tick(30)
    for event in pygame.event.get():

        if event.type == pygame.QUIT:
            run = False

        if event.type == pygame.KEYDOWN:
            print("you pressed " + pygame.key.name(event.key))
            if event.key == pygame.K_q:
                play_sound(0)
            elif event.key == pygame.K_w:
                play_sound(1)
            elif event.key == pygame.K_e:
                play_sound(2)
            elif event.key == pygame.K_r:
                play_sound(3)


pygame.quit()
exit()
# time.sleep(5.5)
# signal.pause()
