#!/usr/bin/env python3
import sys
import os
from os.path import isfile, join
import pygame
from gpiozero import Button
from storage_media import USBDeviceHandler


pygame.init()
winW = pygame.display.Info().current_w * 0.2
winH = pygame.display.Info().current_h * 0.2
window = pygame.display.set_mode((winW, winH))
clock = pygame.time.Clock()

Fullscreen = True
window.fill((205,100,100))
pygame.display.update()


def reset_sounds():
    global sound_array
    sound_array = []
    setup_sounds()


def setup_sounds():
    global sound_array
    global contentlist
    global sound_dir

    print(contentlist)

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


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

    if not cut_current_sound:
        current_sound_index = index

        try:
            channel = sound_array[current_sound_index].play()
        except Exception as X:
            print("no sound with this index: ", current_sound_index)
            print(X)
            return

        while channel.get_busy():
            pygame.time.wait(150)  # ms
            print("Playing...")
            pygame.event.clear()

        print("Finished playing.")

    """ 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.")

    """


def setup_paths(val):
    global contentlist
    global sound_dir
    global sound_dir_local
    global usb_handler

    sound_dir = sound_dir_local
    usbdisks = usb_handler.get_usb_devices()

    if len(usbdisks) > 0:
        sound_dir = usbdisks[0].mountpoint

    contentlist = os.listdir(sound_dir)
    contentlist = sorted(contentlist)
    reset_sounds()


# prepare local paths in case no USB
sound_dir_local = os.getcwd() + "/sounds"
sound_dir = ""

# start USB handler with listener
usb_handler = USBDeviceHandler()
usb_handler.on("example_event", setup_paths)

# prepare sound variables
sound_array = []
cut_current_sound = False
channel = False
current_sound_index = -1

# run empty setup
setup_paths(False)


"""
DEFINE GPIO BUTTONS
"""
btn1 = False
btn2 = False
btn3 = False
btn4 = False

try:
    btn1 = Button(21)
    btn2 = Button(20)
    btn3 = Button(16)
    btn4 = Button(26)
except Exception as X:
    print(X)


run = True
while run:
    clock.tick(25)

    # check pins only if they exist
    if btn1 and btn2 and btn3 and btn4:
        if btn1.is_pressed:
            play_sound(0)
        elif btn2.is_pressed:
            play_sound(1)
        elif btn3.is_pressed:
            play_sound(2)
        elif btn4.is_pressed:
            play_sound(3)

    # check pygame events
    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()
sys.exit()
exit()