'''
Created on Apr 1, 2011
Modified on April 4,5 2011

@author: apsd and alexdutu and ola
'''

import random
import re

# This will be a mapping from strings to lists of strings. The keys
# are the name of a descriptor (such as "adjective"), and the values 
# are a list of strings that fulfill it (such as ["big", "yellow"]).
_tagstore = {}

def read_tagstore(source):
    """
    source supports reading with line-oriented looping,
    e.g., as from a file via open(name) or a URL via
    urllib.open(url)
    
    returns a dictionary containing information from source
    """
    d = {}
    for line in source:
        line = line.strip()
        parts = line.split(":")
        key = parts[0]
        print key
        #  TODO: you must write code here, remove print above
    return d

def read_tagstore_from_file(filename="word_lists.txt"):
    """
    filename is a string denoting a name of a file. 
    This function reads in the file and calls process_word_list_line()
    for each line. This function returns nothing.
    """
    f = open(filename)
    return read_tagstore(f)
    f.close()

def print_out(story,line_width):
    """
    story is a string with whitespace separated words
    prints each word followed by a space using
    line_width characters per line in printing
    """
    curr_len = 0
    for word in story.split():
        if curr_len + len(word) + 1 > line_width:
            # TODO line would be too long, go-to next line
            print
        print word
        # TODO: update curr_len to represent length of line printed so far, change line above
    
    # finish off printing, end the line
    print
    
def get_word_from_user(descriptor):
    """
    descriptor is a string.
    Prompts the user for a word or phrase that matches descriptor,
    and returns it.
    """
    print "enter a",descriptor,
    s = raw_input()
    return s 

def get_word_from_computer(descriptor):
    """
    descriptor is a string.
    This returns a random string from the global variable _tagstore corresponding to 
    the descriptor.
    """
    global _tagstore
    return random.choice(_tagstore[descriptor])
        
def do_mad_lib(template_name):
    """
    template_name is filename of template
    to generate 'madlib', create and show the mad-lib
    """
   
    global _tagstore
    if len(_tagstore) == 0:
        _tagstore = read_tagstore_from_file("word_lists.txt")
   
    f = open(template_name)
    contents = f.read()
    contents = re.sub("\n"," ",contents)
    f.close()
    
    pattern = r"<([^>]+)>"
    iterator = re.finditer(pattern, contents)
    all_tags = [match.group(1) for match in iterator]
    template = re.sub(pattern, "%s", contents)
    
    print contents
    print all_tags
    print template
    
    #  TODO: write code here and remove print statements

if __name__ == "__main__":
    do_mad_lib("labtemplate.txt") 
