'''
Created on Apr 3, 2011
Modified on Apr 4, 2012
@author: ola
'''
import urllib
import rsgModel

def get_one(choices):
    """
    Prompt user to choose one of the items in choices
    a list of strings, returns valid index in choices
    """
    for i,elt in enumerate(choices):
        print "%2d\t%s" % (i+1,elt)
    
    while True:
        print "enter choice (1-%d)" % (len(choices)),
        choice = int(raw_input())
        if not choice in range(1,len(choices)+1):
            print "choice not in range, re-enter"
        else:
            return choice-1

def get_info(url):
    """
    Read URL specified by url and return dictionary
    with categories as keys; corresponding value a list of
    URLS that have story templates for the category
    """
    stream = urllib.urlopen(url)
    d = {}
    for line in stream:
        parts = line.strip().split(",")
        category = parts[1]
        url = parts[3]
        id = parts[0]
        if category in d:
            d[category].append((id,url))
        else:
            d[category] = [(id,url)]
    return d

def read_url(url):
    """
    Read contents of url and return a string of those contents
    """
    print "reading from",url
    return urllib.urlopen(url).read()
        
def process_info(d):
    """
    Parameter d is the dictionary of user-entered
    stories. Choose one category and one url/user from
    that category.
    
    After choice, print the contents of the user-entered story
    found at the chosen url
    """
    index = get_one(d.keys())
    key = list(d.keys())[index]
    print "now choose from:"
    index = get_one([t[0] for t in d[key]])
    #print read_url(d[key][index][1])
    url = d[key][index][1]
    
    d = rsgModel.initialize(urllib.urlopen(url))
    rsgModel.start(d)
    rsgModel.start(d)
    
if __name__ == "__main__":
    
    fall10URL = "http://www.cs.duke.edu/courses/cps006/fall10/assign/rsg/logs.txt"
    spring11URL = "http://www.cs.duke.edu/courses/cps006/spring11/recitation/lab12/logs.txt"
    url = spring11URL
    d = get_info(url)
    process_info(d)
   
