'''
Created on Feb 15, 2011, modified on Feb 26

@author: ola
@author: YOU THE COMPSCI 6 STUDENT WHOSE NAME IS HERE
'''
import tkFileDialog
import Transforms,base64

def get_file_to_open():
    """
    prompt for existing file, return the file (open for reading)
    """
    file = tkFileDialog.askopenfile(title="choose a file")
    return file

def get_file_to_save():
    """
    prompt for new file, user enters name, return file (open for writing)
    """
    file = tkFileDialog.asksaveasfile(title="save file")
    return file

def get_words(file):
    '''
    returns a list of lists, where each nested list
    is one line from file, words in line as elements of nested list
    '''
    words = file.readlines()  
    return [w.split() for w in words]

def choose_transform():
    """
    prompt via commandline for a transform
    return a transform (a function that accepts one string and returns a string)
    return None if user makes bad choice
    """
    funcs = [Transforms.identity, base64.b64decode,base64.b64encode]
    names = ["identity/nothing","base64 decode", "base64 encode"]
    for i,name in enumerate(names):
        print "%d\t%s" % (i+1,name)
    print "enter choice> ",
    choice = int(raw_input())
    if 0 < choice <= len(names):
        return funcs[choice-1]
    return None

def transform(lines, func):
    '''
    apply func to lines, each sublist represents
    a line of words, return a transformed list
    in which each sublist represents a line from
    the original list lines, but in each sublist each
    word has been transformed by applying func to the word
    '''
    return lines

def write_words(file,words):
    """
    words is a list of lists,
    each sublist represents a line to write
    (e.g., of transformed words)
    file is a file open for writing
    write each sublist to the file
    with words on a line separated by whitespace
    and each sublist of words on a line
    """
    for line in words:
        for w in line:
            print w+" ",
        print

def transform_file():
    """
    do the work for this program: prompt user
    for file, get transform function, apply it to each word
    and then write transformed data to a file specified by user
    """
    file = get_file_to_open()
    if file == None:
        return
    words = get_words(file)
    file.close()
    
    func = choose_transform()
    if func == None:
        return
    twords = transform(words,func)
    print "transform done, save file"
    
    file = get_file_to_save()
    if file == None:
        return
    write_words(file,twords)
    file.close();

    
if __name__ == "__main__":
    transform_file()


