#!/usr/bin/env python
#
# Written by Kanishk and Jon (2016)
# Contact Info: jabrahams@hmc.edu
import sys, ast, pprint, difflib

def getd():
    """
    Open and read the dictionary
    """
    try:
        d = open("dictionary", "r+")
    except:
        d = open("dictionary", "w+")
    dstring = d.read()
    d.close()
    try:
        data = ast.literal_eval(dstring)
        return data
    except:
        return {}

def add(word, defin):
    """
    Add a word and its definition to the dictionary
    """
    d = getd()
    d[str(word)] = str(defin)
    writed(d)
    return d

def delete(word):
    """
    Delete a word from the dictionary
    """
    d = getd()
    del d[word]
    writed(d)

def look(word):
    """
    Look up a word in the dictionary
    """
    word = str(word)
    d = getd()
    if word in d:
        print word + " :"
        print d[word]
    else:
        keylist = d.keys()
        closest = difflib.get_close_matches(word, keylist)
        if len(closest) == 0:
            print "Word not found. Consider adding it in?"
            return
        closest = closest[0]
        print "We couldn't find " + word
        print "We found " + closest + " instead"
        print closest + " :"
        print d[closest]


def writed(dstring):
    """
    Write the dictionary to a file
    """
    d = open("dictionary", "w+")
    d.write(str(dstring))
    d.close()

def eth():
    """
    Print out the entire dictionary
    """
    try:
        d = getd()
        pprint.pprint(d, width=1)
    except:
        print "Dictionary not found. Aborting..."

if __name__ == '__main__':
    function = getattr(sys.modules[__name__], sys.argv[1])
    try:
    	word = sys.argv[2]
    	try:
        	defin = sys.argv[3]
        	function(word, defin)
        except:
        	function(word)
    except:
    	function()
