#!/your/path/to/python/here

import cgi
import os
import json

inputs = cgi.FieldStorage()

print("Content-Type: text/html")
print("")

dictionary = {}

# Error handling technique 1:
if os.path.exists("dictionary.json"):
    f = open("dictionary.json","r")
    file_contents = f.read()
    dictionary = json.loads(file_contents)

if "definition" in inputs:
    word = inputs["word"].value
    definition = inputs["definition"].value
    dictionary[word] = definition
    f = open("dictionary.json","w")
    output = json.dumps(dictionary)
    f.write(output)
    f.close()
    print("Thanks for the word!")

elif "word" in inputs:
    user_text = inputs["word"].value

    if user_text in dictionary:
        print("The definition of {w} is:".format(w=user_text))
        print("  " + dictionary[user_text])
    else:
        print("hm, I don't know the word " + user_text)
        html = """
        <form action='/cgi-bin/dictionary.py'>
        <input type='hidden' name='word' value='{w}'>
        Enter a definition for it: <input name='definition' type='text'>
        <input type='submit' value='Lookup'>
        </form>
        """.format(w=user_text)
        print(html)
        exit()

print("I know {num} words.".format(num=len(dictionary)))
html = """
<form action='/cgi-bin/dictionary.py'>
Type a word: <input name='word' type='text'>
<input type='submit' value='Lookup'>
</form>
"""
print(html)