import threading, string, re, sys, time
import phoneme
import rhymecore

dict_path = "../dict/cmudict.0.6"

dict_data = {}
dict_thread = None

def _normalize_word(word):
    return word.strip().upper()

class DictLoader(threading.Thread):

    def run(self):

        global dict_data, dict_rhymes

        t1 = time.time()
        in_dict = file(dict_path)
        for line in in_dict.xreadlines():
            if line[:2] != "##":
                line = line.strip()
                i = line.find(" ")
                if i != -1:
                    word = _normalize_word(line[:i])
                    pronunciation = line[i:].strip()
                    decomp = phoneme.decomp_from_string(pronunciation)

                    dict_data[word] = decomp
                    rhymecore.index_word(word, decomp)
        t2 = time.time()
        print "Loaded dictionary in %.2fs" % (t2-t1)

        in_dict.close()

dict_thread = DictLoader()
dict_thread.start()

def get_decomp(word):
    if dict_thread.isAlive():
        dict_thread.join()

    return dict_data.get(_normalize_word(word))

def iterwords():
    if dict_thread.isAlive():
        dict_thread.join()

    return dict_data.iteritems()


###
### Rhyme Computations
###

def all_rhymes(word, slant_rhyme=0):
    phons = pronunciation(word)
    if not phons:
        return None

    key = rhyme_stem_key(phons, word)
    raw_rhymes = dict_rhymes.get(key, [])
    rhymes = []
    for word, word_phons in raw_rhymes:
        if is_rhyme(phons, word_phons, slant_rhyme=slant_rhyme):
            rhymes.append(word)
    return rhymes
