import bottle
import words

# This function is called when we visit the root of the server
# (lec23.epmikida.repl.co)
@bottle.route("/")
def serveRoot():
  # This function returns an HTML string for the browser to display
  response = "<html><body><p>"
  response = response + "Hello from the server!"
  response = response + "</p></body></html>"
  return response

# This function is called when we visit the /static page
# (lec23.epmikida.repl.co/static)
@bottle.route("/static")
def serveStaticPage():
  # It returns the contents of index.html
  return bottle.static_file("index.html",root="")

# This function is called when we visit the /hello page
# (lec23.epmikida.repl.co/hello)
@bottle.route("/hello")
def serveHello():
  replacements = {}
  # bottle.request.query is a dictionary containing the key-value
  # pairs from the query string
  # Here we try to get the value of "name" if it exists, otherwise
  # just default to using "World"
  replacements["name"] = bottle.request.query.get("name","World")
  # We then return the contents of hello.html but with the
  # templated portions filled in from our replacements dictionary
  return bottle.template("hello.html",replacements)
  
# This function is called when we visit the /word page
# (lec23.epmikida.repl.co/word)
@bottle.route("/word")
def serveWord():
    # bottle.request.query is a dictionary containing the key-value
    # pairs from the query string
    # Here we try to get the value of "w" if it exists, otherwise
    # get a random word
    # The randomWord function is defined by us in words.py
    w = bottle.request.query.get("w", words.randomWord())
    c = words.frankenDict.get(w,0)
    # Return the contents of words.html with the templated
    # portions replaced by the word and count that we looked up
    # from the frankenstein dictionary.
    return bottle.template("words.html",{"word":w,"count":c})

bottle.run(host="0.0.0.0", port=8080, debug=True)