import os
import pygame, pygame.image
from pygame.locals import *

import random

import options


characters=["tim", "tyger", "tess", "woody"]
categories=["long-bad", "long-good", "short-bad", "short-good"]

g_charname="woody"
g_channel_num=0

g_cur_time=0.0
g_queued_filename=None
g_queued_time=-30.0

voices={}

#voices["woody"][0]["short_good"][3] is a filename


def select_character(char_name):

    assert char_name in characters
    
    global g_charname
    g_charname=char_name



def select_channel(channel_num):
    global g_channel_num
    g_channel_num=channel_num%len(voices[g_charname])

def select_random_channel():
    global g_channel_num
    g_channel_num=random.randrange(len(voices[g_charname]))


def update(dt):
    if not options.g_sounds:
        return

    if not pygame.mixer:
        return
    
    # check to see if a voice is queued
    # if so, play it.
    global g_cur_time
    global g_queued_filename
    global g_queued_time

    g_cur_time += dt

    if g_queued_filename and g_queued_time<g_cur_time:
        s=pygame.mixer.Sound(g_queued_filename)
        s.play()
        g_queued_filename = None
        g_queued_time = g_cur_time


def queue(sound_category, force=0):
    global g_queued_filename
    global g_queued_time

    delay=0.5
    if not force:
        if g_cur_time-g_queued_time<delay:
            return

    g_queued_time=g_cur_time+delay
    g_queued_filename=pick_random_filename(sound_category)




def pick_random_filename(sound_category):
    return random.choice(voices[g_charname][g_channel_num][sound_category])
    

def findfiles():
    base="data/sounds/voiceovers"
    for cn in characters:
        charDir=os.path.join(base, cn)
        actors=os.listdir(charDir)
        actorList=[]
        if "placeholder.txt" in actors:
            actors.remove("placeholder.txt")

        for a in actors:
            actorPath=os.path.join(charDir,a)

            soundCategories={}

            for c in categories:
                catPath=os.path.join(actorPath,c)
                soundList=[]
                try:
                    for soundname in os.listdir(catPath):
                        if soundname=="placeholder.txt":
                            continue
                        filePath=os.path.join(catPath,soundname)
                        soundList.append(filePath)
                except:
                    pass

                soundCategories[c]=soundList
            actorList.append(soundCategories)
        voices[cn]=actorList
