from time import time
from flask import Flask, Response,request

app = Flask(__name__)

lst = []  # List of (name, complete time) for all items ever added.

# Returns a textual description of all items either uncompleted or completed
# within the last 5 seconds.
@app.route('/list')
def todo_list():
  since = time() - 5
  text = '\n'.join(map(lambda t: t[0] + "\t(completed)" if t[1] > 0 else t[0],
      filter(lambda t: t[1] < 0 or since <= t[1], lst)))
  return Response(text, mimetype='text/plain')

# Adds the given item to the list or, if it is already completed, changes it
# back to non-completed.
@app.route('/add', methods=['POST'])
def todo_add():
  name = request.args.get('name')
  names = list(map(lambda t: t[0], lst))
  try:
    index = names.index(name)
    if lst[index][1] >= 0:
      lst[index][1] = -1   # change back to not completed
      return "added"
    else:
      return "added already"
  except:
    lst.append([name, -1])
    return "added"

# Marks the given item as having just been completed.
@app.route('/completed', methods=['POST'])
def todo_completed():
  name = request.args.get('name')
  names = list(map(lambda t: t[0], lst))
  index = names.index(name)
  lst[index][1] = time()
  return "completed"